/****************************************************************************** * FILE: bug4fix.c * DESCRIPTION: * This is just one way to resolve the synchronization problem demonstrated * by bug4.c. A check is made in sub1 to make sure the pthread_cond_wait() * call is not made if the value of count is not what it expects. Its work is * also placed after it is awakened, while count is locked. * SOURCE: 07/06/05 Blaise Barney * LAST REVISED: 01/29/09 Blaise Barney ******************************************************************************/ #include #include #include /* Define and scope what needs to be seen by everyone */ #define NUM_THREADS 3 #define ITERATIONS 10 #define THRESHOLD 12 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; /* 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); if (count < THRESHOLD) { 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); /* do some work */ sleep(1); count++; finalresult += myresult; printf("sub1: thread=%ld count now equals=%d myresult=%e. Done.\n", tid,count,myresult); } else { printf("sub1: count=%d. Not as expected.",count); printf(" Probably missed signal. Skipping work and exiting.\n"); } 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