. . .
Although there is a function sem_getvalue() which will return the current value of a
semaphore, it is virtually impossible to use correctly because what it returns is what the value of
the semaphore was. By the time you use the value it returned, it may well have changed. If you
find yourself using sem_getvalue(), look twice; there's probably a better way to do what you
Java does not include semaphores as one of its base classes, but they are easily implemented and
we have done so in our extensions package. Our Semaphore class behaves exactly as POSIX
semaphores do (ignoring UNIX signal issues). Win32 implements counting semaphores with
similar definitions.
In the execution graph (Figure 6-7) we see the operation of Code Example 6-11. Notice that when
T1's decrement attempt fails, it simply goes to sleep and tries it again later. Another thread could
jump in and decrement the value just as thread T1 was waking up, in which case T1 would have to
go back to sleep. As with mutexes, this is usually not a problem.
Figure 6-7. Execution Graph of the Operation of a Semaphore
A typical use of semaphores is in Code Example 6-12. This is a producer/consumer example in
which one thread is continually receiving requests from the net, which it adds to a list, while the
other thread is busy removing items from that list and processing them. It is particularly
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks