Creating a Barrier
A condition variable cannot easily be used to synchronize a set of threads. If the thread that calls the broadcast member function executes the call before all threads are waiting, then one or more of the threads will miss the broadcast and will remain blocked.
The barrier gets round this problem in the case where the application knows how many threads are going to wait at the barrier. In this case, the threads call the member function wait of the barrier and the barrier class will call broadcast—rather than wait—for the last thread to arrive so that it will wake up all the other waiting threads. You do not need to know which will be the last thread to arrive at the barrier. Hence, the barrier class provides two main member functions, wait to wait on the barrier and newCount to change the number of threads that are to wait at the barrier. The original count of the number of threads that are to wait at the barrier is the first parameter to the IlsBarrier constructor.
Here is an example:
IlsBarrier barrier(3);
IlsThread* t1 = new IlsThread(runToBarrier, &barrier);
IlsThread* t2 = new IlsThread(runToBarrier, &barrier);
// now wait for the other threads to reach the barrier
barrier.wait();
void runToBarrier(IlsAny data)
{
IlsBarrier* b = (IlsBarrier *) data;
...
b->wait();
...
}
A barrier can also provide a private mutex as an argument to the constructor. For details, see
Condition Variables. If a private mutex is provided, then the application must lock and unlock the mutex explicitly before and after any calls to the barrier.
An example of this is shown below:
IlsUnsafeMutex mutex;
IlsBarrier barrier(3, 0, 0, &mutex);
IlsThread* t1 = new IlsThread(runToBarrierM, &barrier);
IlsThread* t2 = new IlsThread(runToBarrierM, &barrier);
// now wait for the other threads to reach the barrier
mutex.lock();
barrier.wait();
mutex.unlock();
Version 6.3
Copyright © 2018, Rogue Wave Software, Inc. All Rights Reserved.