Question: Write a program that is similar to cond1.c except that: thread1: increments count only when count is currently an even number thread2: increments count only

Write a program that is similar to cond1.c except that: thread1: increments count only when count is currently an even number thread2: increments count only when count is currently an odd number

Further Requirements: -a thread prints the value of count AFTER the increment is performed. -threads terminate when count reaches COUNT_DONE -after threads terminate, main prints the final count (like cond1.c does). -thread2 may test count to determine its parity, but thread1 may not. -thread1 always increments count when it is signalled (unless it terminates) -Your program output should look identical to this: Counter value functionEven: 1 Counter value functionOdd: 2 Counter value functionEven: 3 Counter value functionOdd: 4 Counter value functionEven: 5 Counter value functionOdd: 6 Counter value functionEven: 7 Counter value functionOdd: 8 Counter value functionEven: 9 Counter value functionOdd: 10 Final count: 10

here is cond1.c for reference:

#include #include #include

pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;

void *functionCount1(); void *functionCount2(); int count = 0; #define COUNT_DONE 10 #define COUNT_HALT1 3 #define COUNT_HALT2 6

int main() { pthread_t thread1, thread2;

pthread_create( &thread1, NULL, &functionCount1, NULL); pthread_create( &thread2, NULL, &functionCount2, NULL);

pthread_join( thread1, NULL); pthread_join( thread2, NULL);

printf("Final count: %d ",count);

exit(0); }

// Write numbers 1-3 and 8-10 as permitted by functionCount2()

void *functionCount1() { 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 varialbe in functionCount2() signaled. pthread_cond_wait( &condition_var, &count_mutex ); count++; printf("Counter value functionCount1: %d ",count);

pthread_mutex_unlock( &count_mutex );

if(count >= COUNT_DONE) return(NULL); } }

// Write numbers 4-7

void *functionCount2() { 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 ",count); }

pthread_mutex_unlock( &count_mutex );

if(count >= COUNT_DONE) return(NULL); }

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!