#include <Barrier.h>
Inheritance diagram for ZThread::Barrier::
Public Methods | |
Barrier (int thr, bool resets=true) throw (Synchronization_Exception) | |
virtual | ~Barrier () throw () |
virtual void | acquire () throw (Synchronization_Exception) |
virtual bool | tryAcquire (unsigned long timeout) throw (Synchronization_Exception) |
virtual void | release () throw (Synchronization_Exception) |
This provides a simple mechanism for making sure all threads working on some data have reached a specific point before the program continues.
After enough threads have reached a Barriers threshold, the Barrier will reset and can be used again.
An example:
This very brief example attempts to illustrate several threads working on a shared set of data. These tasks may reach some critical point at which they want to be certain that no other threads are still working on that data.
Barrier ready(4), restart(4) class RED : public Runnable { public: virtual ~RED() {} virtual void run() { try { // Start doing something to some shared data cout << "RED is waiting..." << endl; Thread::sleep(2000); ready.acquire(); // critical point restart.acquire(); } catch(...) { cerr << "RED Unexcpected Exception!" << endl; } } }; // BLUE() & GREEN() have similar definitions int main() { Thread th[3]; RED r, BLUE b, GREEN g; th.run(&r); th.run(&b); th.run(&g); ready.acquire(); // After all the workers reach the barrier execution // will continue // switch the data set or someother operation you need to be // sure the working threads will not interrupt ... restart.acquire(); // Unblock the threads waiting on this barrier }
NOTE: Barriers are generally more useful in SMP architectures
|
Create a new Barrier that waits for n threads. This is the threshold of the Barrier.
|
|
Destroy the Barrier |
|
A thread attempting to invoke the acquire method of a Barrier will be blocked until enough threads have invoked the method and the threshold is met.
Reimplemented from ZThread::Lockable. |
|
The release method has no effect for a Barrier. A thread is simply blocked by an acquire() attempt or not.
Reimplemented from ZThread::Lockable. |
|
This method can be used to quickly test weather or not the Barrier is at it's threshold. If you chose a lock, such as a FastMutex, that does not support the tryAcquire method then this will block until the Barrier has reached its threshold.
Reimplemented from ZThread::Lockable. |