If the value of the semaphore is zero, the mutex will be released, and the thread will then go to
sleep. Upon waking up, the thread must repeat the operation, reacquiring the mutex and testing the
The operation of semPost() is quite simple. It locks the mutex, increments the value, releases
the mutex, and wakes up one sleeper (if there is one). The results are exactly what you expect.
Even though you have no idea what the scheduling order might be, it is impossible to accidentally
decrement the value below zero, and no thread can ever get "stuck" on the sleep queue when the
value is greater than zero. There are timing gaps where things look momentarily inconsistent, and
it is possible for a thread to be awakened by mistake, but the end results are always correct.
A semaphore is perfect for situations where you want to count things and have threads sleep when
some limit is hit. If you wish to count up to some number, say for a list limited to ten items, you
simply view the semaphore as counting the number of "spaces" in the list, initialize it to ten, and
count down.
There are occasions when you want the same kind of sleeping behavior as with semaphores, but
your test is more complex than just "Is v > 0?"
Condition Variables
Figure 6-9 shows a flowchart for a generalization on semaphores. Here the mutex is visible to the
programmer and the condition is arbitrary. The programmer is responsible for locking and
unlocking the mutex, testing and changing the condition, and waking up sleepers. Otherwise, it is
exactly like a semaphore. We'll look at POSIX condition variables first, then see how Java
implements the same concept.
Figure 6-9. Flowchart for Condition Variables
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks