img
. . .
if (workpile.stop)
break;
// Put the Item on the list!
workpile.mutex.unlock();
workpile.consumerCV.condSignal();
// OUTSIDE the CS
}
workpile.mutex.unlock();
// Unlock!
barrier.barrierPost();
// We're exiting
}
}
Notice that we've moved the call to condSignal() outside the critical section. This is its normal
position.
When we set stop to true, we will need to wake up all threads that might be sleeping. In Code
Example 6-24, we spawn a thread to set stop true after 4 seconds. After it's set, the thread calls
condBroadcast() to wake up all the worker threads. We would do the same if it were a button
we were using, or any other method. Notice that we must lock the mutex before changing the
value of stop; otherwise, we'll be subject to the lost wakeup problem.
Example 6-24 Stoppable Producer/Consumer Model (Stopper)
public class Stopper implements Runnable {
...
public void run() {
InterruptibleThread.sleep(delay);
System.out.println("Stopping...");
workpile.mutex.lock();
workpile.stop = true;
workpile.mutex.unlock();
workpile.consumerCV.condBroadcast();
workpile.producerCV.condBroadcast();
}
}
Finally, in this bit of code from main() (Code Example 6-25), we see how we can synchronize
on the exiting of the threads and the emptying of the queue. First we start them all up. Then we
wait for all the threads to complete their work [they'll probably exit a couple of microseconds after
they call semPost(); however, we don't really care]. After they have all completed their work,
we can set stop back to false. (What if we didn't wait for all the threads to finish?) Then we
create the consumers and wait for them to empty the queue. (Notice how we reuse the condition
variable producerCV here. We could have used a third condition variable, but the extra
efficiency we'd get would be absurdly small.) Once the queue is empty, we start up the producers
again.
Example 6-25 Stoppable Producer/Consumer Model (Starting Up and Shutting
Down in main()
public static void main(String argv[]) {
...
barrier = new SingleBarrier(nConsumers + nProducers);
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home