/***************************************************** ** Barrier.cpp ** ** ----------- ** ** ** ** A simple barrier class that prevents threads ** ** from accessing a critical section until a ** ** number of threads (specified by "threshold") ** ** agree that it is time. Once the threshold is ** ** met, all currently waiting threads are ** ** released and may resume processing. ** ** ** ** Note: This builds on pthreads!! ** ** ** ** Chris Wyman (2/12/2007) ** *****************************************************/ #include "Barrier.h" Barrier::Barrier( int threshold ) { pthread_mutex_init (&mutex, NULL); pthread_cond_init (&condVar[0], NULL); pthread_cond_init (&condVar[1], NULL); threadThreshold = threshold; numWaiting = 0; currCondVar = 0; } Barrier::~Barrier( void ) { pthread_mutex_destroy( &mutex ); pthread_cond_destroy( &condVar[0] ); pthread_cond_destroy( &condVar[1] ); } void Barrier::Wait( void ) { // Lock the mutex. We're going into a critical section pthread_mutex_lock( &mutex ); // Grab a pointer to the conditionVariable we're using this time through the barrier pthread_cond_t *cond = &condVar[currCondVar]; // We've got another thread waiting here at the barrier... numWaiting++; if (numWaiting < threadThreshold) // Then we need to wait. Go to sleep. pthread_cond_wait( cond, &mutex ); else { // Reset the barrier count. numWaiting=0; // Switch to use the other condition variable next time currCondVar = 1-currCondVar; // We're the last thread. Wake others up. pthread_cond_broadcast( cond ); } // Done in the critical section, release the lock pthread_mutex_unlock( &mutex ); }