/****************************************************************************** * FILE: bug4.c * DESCRIPTION: * This program demonstrates a condition variable race/synchronization * problem. It resembles the condvar.c program. One possible solution can * be found in bug4fix.c * SOURCE: 07/06/05 Blaise Barney * LAST REVISED: 01/29/09 Blaise Barney ******************************************************************************/ #include #include #include #include #include /* Define and scope what needs to be seen by everyone */ #define NUM_THREADS 3 #define ITERATIONS 3 #define THRESHOLD 6 int count = 0; double finalresult=0.0; pthread_mutex_t count_mutex; pthread_cond_t count_condvar; void *sub1(void *t) { int i; long tid = (long)t; double myresult=0.0; /* do some work */ sleep(1); /* Lock mutex and wait for signal only if count is what is expected. Note that the pthread_cond_wait routine will automatically and atomically unlock mutex while it waits. Also, note that if THRESHOLD is reached before this routine is run by the waiting thread, the loop will be skipped to prevent pthread_cond_wait from never returning, and that this thread's work is now done within the mutex lock of count. */ pthread_mutex_lock(&count_mutex); printf("sub1: thread=%ld going into wait. count=%d\n",tid,count); pthread_cond_wait(&count_condvar, &count_mutex); printf("sub1: thread=%ld Condition variable signal received.",tid); printf(" count=%d\n",count); count++; finalresult += myresult; printf("sub1: thread=%ld count now equals=%d myresult=%e. Done.\n", tid,count,myresult); pthread_mutex_unlock(&count_mutex); pthread_exit(NULL); } void *sub2(void *t) { int j,i; long tid = (long)t; double myresult=0.0; for (i=0; i