img
. .
public void run() {
Item item;
while (true) {
item = server.get();
workpile.add(item);
s.semPost();
}
}
}
The list in both examples is unbounded and may continue to grow longer until memory is
exhausted. This is a problem with our example code that must be solved. You should be able to
come up with a solution yourself now. We'll get to it a bit later.
Using Barriers to Count Exiting Threads
Sometimes we do want to know when a set of threads have completed their work. One way of
doing this is to use a single barrier (distinct from the Barriers). Each exiting thread will increment
the barrier's value, and the thread waiting for them will wait until the value is the number of
threads being waited for. This gives a convenient replacement for calling thread.join(). We'll
be using single barriers regularly for this purpose.
We'll show the code in Single Barriers , but the gist of it is that worker threads call
barrier.barrierPost() as they exit and the master thread calls barrier.barrierWait()
(barrier has been initialized to the number of worker threads). Thus the master thread will wait
until all the workers are done. (We don't actually care exactly when the worker threads exit.)
A Different View of Semaphores
Now let's look at a different picture of how a semaphore works. Figure 6-8 depicts the actual
operation of semWait() and semPost() in our extensions package. As the value of the
semaphore is a shared data item, it must be protected in a synchronized section (or logical
equivalent). The first thing semWait() does is enter that synchronized section (locks the mutex).
Then it checks the value. If it is greater than zero, the value is decremented, the mutex is released,
and semWait() returns.
Figure 6-8. Flowchart for Semaphores
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home