The RWBarrier Class
The RWBarrier class uses condition synchronization to implement another form of synchronization called a barrier or rendezvous. This mechanism synchronizes the activities of a group of two or more threads.
A barrier is initialized with the number of threads that it synchronizes. As each thread in the group completes some computational stage or activity, it calls the wait() method of the barrier, where it is blocked until the remaining threads have also entered the barrier. When the last thread calls wait(), all of the blocked threads are released.
Example 38 demonstrates the use of the barrier to coordinate the activities of a group of threads.
Example 38 – Using barrier synchronization
#include <rw/rstream.h>
#include <rw/thread/rwtMakeThreadFunction.h>
#include <rw/sync/RWBarrier.h>
 
void heave_ho(RWBarrier& barrier, size_t pulls)
{
for (size_t i=0; i<pulls; i++) {
cout << "Heave!” << endl;
barrier.wait();
cout << "Ho!” << endl;
barrier.wait();
}
}
void tugThatLine(size_t pulls)
{
const size_t count=5; // Number of sailors
RWThread thread[count];
RWBarrier barrier(count);
size_t i;
// Create the threads
for (i=0; i<count; i++) {
thread[i] = rwMakeThreadFunctionGA2(void,
heave_ho,
RWBarrier&,
barrier,
size_t,
pulls);
}
 
// Start the threads
for (i=0; i<count; i++)
thread[i].start();
 
// Wait for the threads to finish
for (i=0; i<count; i++)
thread[i].join();
}
 
void main()
{
tugThatLine(3); // Ask for three good tugs!
}
The output is:
 
Heave!
Heave!
Heave!
Heave!
Heave!
Ho!
Ho!
Ho!
Ho!
Ho!
.
.
.
(for a total of three times)