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:
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:
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