//compile gcc -o cond1.exe -pthread cond1.c #include #include #include #define COUNT_DONE 10 #define COUNT_HALT1 3 #define COUNT_HALT2 6 //global variables pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER; int count = 0; //thread functions void *functionCount1(void *); void *functionCount2(void *); int main(void ) { pthread_t thread1, thread2; int val = 0; if( pthread_create( &thread1, NULL, functionCount1, (void *)&val) != 0) { fprintf(stderr,"pthread_creat() failed\n"); exit(1); } if( pthread_create( &thread2, NULL, functionCount2, (void *)&val) != 0 ) { fprintf(stderr,"Second pthread_creat() failed\n"); exit(1); } pthread_join( thread1, NULL); pthread_join( thread2, NULL); printf("Final count: %d\n",count); exit(EXIT_SUCCESS); } // // Write numbers 1-3 and 8-10 as permitted by functionCount2() void *functionCount1( void * val) { for(;;) { // Lock mutex and then wait for signal to relase mutex pthread_mutex_lock( &count_mutex ); // Wait while functionCount2() operates on count // mutex unlocked if condition variable in functionCount2() signaled. pthread_cond_wait( &condition_var, &count_mutex ); count++; printf("Counter value functionCount1: %d\n",count); pthread_mutex_unlock( &count_mutex ); if(count >= COUNT_DONE) pthread_exit(NULL); } } // Write numbers 4-7 void *functionCount2(void * val) { for(;;) { pthread_mutex_lock( &count_mutex ); if( count < COUNT_HALT1 || count > COUNT_HALT2 ) { // Condition of if statement has been met. // Signal to free waiting thread by freeing the mutex. // Note: functionCount1() is now permitted to modify "count". pthread_cond_signal( &condition_var ); } else { count++; printf("Counter value functionCount2: %d\n",count); } pthread_mutex_unlock( &count_mutex ); if(count >= COUNT_DONE) pthread_exit(NULL); } }