CyclicBarrier
class is a synchronization aid that
allows a set of threads to wait for the entire set of threads to
reach a common barrier point. CyclicBarrier
is
constructed with an integer argument, which determines the number of
threads in the group. When one thread arrives at the barrier (by
calling CyclicBarrier.await()
), it blocks until all
threads have arrived at the barrier, at which point all the threads
are then allowed to continue executing. This action is similar to what many
families (try to) do at the mall -- family members go their separate
ways, and everyone agrees to meet at the movie theater at 1:00. When
you get to the movie theater and not everyone is there, you sit and
wait for everyone else to arrive. Then everyone can leave together.
The barrier is called cyclic because it is reusable; once all the threads have met up at the barrier and been released, the barrier is reinitialized to its initial state.
You can also specify a timeout when waiting at the barrier; if by that time the rest of the threads have not arrived at the barrier, the barrier is considered broken and all threads that are waiting receive a
BrokenBarrierException
.
The code example below creates a
CyclicBarrier
and
launches a set of threads that will each compute a portion of a
problem, wait for all the other threads to finish, and then check to
see if the solution has converged. If not, each worker thread will
begin another iteration. This example uses a variant of
CyclicBarrier
that lets you register a
Runnable
that is executed whenever all the threads
arrive at the barrier but before any of them are released.class Solver { // Code sketch void solve(final Problem p, int nThreads) { final CyclicBarrier barrier = new CyclicBarrier(nThreads, new Runnable() { public void run() { p.checkConvergence(); }} ); for (int i = 0; i < nThreads; ++i) { final int id = i; Runnable worker = new Runnable() { final Segment segment = p.createSegment(id); public void run() { try { while (!p.converged()) { segment.update(); barrier.await(); } } catch(Exception e) { return; } } }; new Thread(worker).start(); } }
Kindly provide your valuable feedback in comment box.
No comments:
Post a Comment