img
. . .
It's interesting to look at the design of a single barrier (Code Example 7-5). Notice in particular
that the barrier must account for the situation where one waiter has been released but hasn't
finished. (It's been awakened but hasn't gotten the CPU yet.) If one of the posters hurries around
its loop and tries to use the single barrier again (before the waiter is done), there could be trouble!
This is handled by counting both the number of posters and the number of waiters that have
completed the code. When you write your own synchronization variables, you should carefully
consider how those synchronization variables will work the second time around. Also notice how
interrupted exceptions are handled. (We'll talk about this in detail in Defined
Cancellation/Interruption Points.)
Example 7-5 Implementing Single Barriers in Java
//
Extensions/SingleBarrier.java
/*
Unlike a Barrier, where all threads wait until all are ready, with
this Threads may indicate that they've completed their job by doing
a
barrierPost() and then continue.  Later, other threads (or the same)
may wait until everyone has done a barrierPost() by doing a
barrierWait().
By default, assume a single waiter.  You must know the number of
threads that will be posting and the number that will be waiting.
*/
package Extensions;
import java.io.*;
public class SingleBarrier {
int currentPosters = 0, totalPosters = 0;
int passedWaiters = 0, totalWaiters = 1;
public SingleBarrier (int i) {
totalPosters = i;
}
public SingleBarrier (int i, int j) {
totalPosters = i;
totalWaiters = j;
}
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home