/***************************************************************************** * 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: bug4.cvl * DESCRIPTION: * This program demonstrates a condition variable race/synchronization * problem. It resembles the condvar.cvl program. One possible solution can * be found in bug4fix.cvl * Command line execution: * civl verify -inputNUM_THREADS=3 -inputITERATIONS=10 -inputTHRESHOLD=12 bug4.cvl ******************************************************************************/ #include "pthread.cvh" #include #include #include #include "math.cvh" /* 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; /* do some work */ //sleep(1); Removed, unnecessary /* 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=%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); count++; finalresult += myresult; printf("sub1: thread=%d count now equals=%d myresult=%e. Done.\n",tid,count,myresult); // Removed l from %ld 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