// threads using condition wait and signal // #include #include #include // for sleep() #include // for exit() #define EXIT(msg) { perror(msg); exit(1); } #define Pthread_create(a,b,c,d) if( pthread_create(a,b,c,d) ) EXIT("pthread_create") #define Pthread_mutex_lock(a) if( pthread_mutex_lock(a) ) EXIT("pthread_mutex_lock") #define Pthread_mutex_unlock(a) if( pthread_mutex_unlock(a) ) EXIT("pthread_mutex_unlock") #define Pthread_cond_wait(a,b) if( pthread_cond_wait(a,b) ) EXIT("pthread_cond_wait") #define Pthread_cond_signal(a) if( pthread_cond_signal(a) ) EXIT("pthread_cond_signal") #define NT 4 // number of threads pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int count[NT] = { 5, 4, 3, 2 }; void *f( void *v) { int *p = v; while( *p > 0) { sleep(1); --*p; } // slowly decrement my counter Pthread_mutex_lock(&lock); Pthread_cond_signal(&cond); Pthread_mutex_unlock(&lock); return 0; } int main( void) { pthread_t t[NT]; // create the threads // for( int i = 0; i < NT; ++i) Pthread_create( &t[i], 0, f, &count[i]); // wait until any one thread is finished // Pthread_mutex_lock(&lock); Pthread_cond_wait(&cond, &lock); Pthread_mutex_unlock(&lock); // stop all threads // for( int i = 0; i < NT; ++i) pthread_cancel( t[i]); }