/***************************************************************************** * SOURCE: This is a translation of a Pthread program from the Lawrence Livermore * Computing Center POSIX Threads Programming Exercise at: * https://computing.llnl.gov/tutorials/pthreads/exercise.html * SUPERSOURCE: Adapted from example code in "Pthreads Programming", B. Nichols * et al. O'Reilly and Associates. * FILE: bug4fix.cvl * DESCRIPTION: * This is just one way to resolve the synchronization problem demonstrated * by bug4.cvl. 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. * Command line execution: * civl verify -inputNUM_THREADS=3 -inputITERATIONS=10 -inputTHRESHOLD=12 bug4fix.cvl ******************************************************************************/ #include #include #include /* Define and scope what needs to be seen by everyone */ $input int NUM_THREADS; $input int ITERATIONS; $input int THRESHOLD; 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=%d going into wait. count=%d\n",tid,count); // Removed l from %ld pthread_cond_wait(&count_condvar, &count_mutex); printf("sub1: thread=%d Condition variable signal received.",tid); // Removed l from %ld printf(" count=%d\n",count); /* do some work */ //sleep(1); count++; finalresult += myresult; printf("sub1: thread=%d count now equals=%d myresult=%e. Done.\n",tid,count,myresult); // Removed l from %ld } 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, false, NULL, 0); //Different parameters } void *sub2(void *t) { int j,i; long tid = (long)*t; double myresult=0.0; for (i=0; i