/****************************************************************************** * FILE: condVarBroadcast.cpp * DESCRIPTION: * Example code for using Pthreads condition variables. The main thread * creates threads. Each thread waits on a condition. After sleeping 3 seconds, * main thread broadcasts a signal to all threads, which then complete. * LAST REVISED: 04/07/07 Dr. Spiegel ******************************************************************************/ #include #include #include #include #include #ifdef __WIN32__ #include #else #include #endif using namespace std; pthread_mutex_t thr_mutex; pthread_cond_t cv; void msleep(int milliseconds) { #ifdef __WIN32__ Sleep(milliseconds); #else usleep(static_cast(milliseconds)*1000); //or use nanosleep on platforms where it's needed #endif } void *doThread(void *thrNum) { cerr << "Thread " << *((int *)thrNum) << " about to lock mutex\n"; pthread_mutex_lock(&thr_mutex); /* Lock mutex and wait for signal. Note that the pthread_cond_wait routine will automatically and atomically unlock mutex while it waits. */ cerr << "Thread " << *((int *)thrNum) << " about to do condition wait\n"; pthread_cond_wait(&cv, &thr_mutex); cerr << "Thread " << *((int *)thrNum) << " signaled\n"; // when signaled, mutex is locked. Unlock it. pthread_mutex_unlock(&thr_mutex); pthread_exit(NULL); } int main(int argc, char *argv[]) { int i, rc; pthread_t *threads; if (argc!=2) { cerr << "Form: condVarBroadcast <# threads>\n"; return(-1); } threads=new pthread_t[atoi(argv[1])]; pthread_attr_t attr; /* Initialize mutex and condition variable objects */ pthread_mutex_init(&thr_mutex, NULL); pthread_cond_init (&cv, NULL); /* For portability, explicitly create threads in a joinable state */ pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i=0;i