2.8 Inter-thread Synchronization

Just because threads do share all static variables and objects that are dynamically allocated, you should not assume it is easy to synchronize threads that are executing in parallel. Once preemption is supported, thread sychronization becomes very difficult with just global variables. When inter-thread synchronization is poorly planned or designed, bugs tend to pop up randomly. At random times a program crashes with random symptoms. This makes debugging extremely difficult. When an RTK provides well thought-out and safe inter-thread synchronization, the application programmer can save much development time while producing reliable application software.

One common method to synchronize is through the use of semiphores. In the context of operating system concepts, a semiphore is a ``magic'' counter that can be initialzied, decremented (P) or incremented (V). Conceptually, this is what happens when a semiphore is decremented:


\begin{algorithmic}
\IF{semaphore is zero}
\STATE block thread until semaphore is greater than zero
\ENDIF
\STATE decrement semaphore value
\end{algorithmic}

The increment operation does not have any conceptual specialization, it simply increases the value of a semaphore (by one).

In implementation, however, an efficient kernel uses a queue for each semaphore. This way, the ``block'' operation translates to adding a thread to the tail of a wait queue. As the value of a semaphore increments to non-zero, the thread at the head of the queue is removed and it becomes active again.

It is easy to use a semaphore to ensure mutual exclusion (mutex) of a piece of code. A semaphore is initialized to have a value of 1. The code that needs to be protected (from multiple thread invocation) looks like the following:


\begin{algorithmic}
\STATE decrement value of mutex semaphore
\STATE perform protected code
\STATE increment value of mutex semaphore
\end{algorithmic}

This way, if one thread is already executing the protected code, all other threads cannot gain entry because the semaphore value is already zero (or less). However, as soon as the thread that successfully execute the code exits the protected code, the semaphore value is incremented, and one other waiting thread gains access to the protected code.

Copyright © 2008-10-25 by Tak Auyeung