conditional - Output for sample code for an upcoming exam concerning pthread -
pthread_mutex_t mutex = pthread_mutex_initializer; pthread_cond_t cond = pthread_cond_initializer; int token = 2; int value = 3; void * red ( void *arg ) { int myid = * ((int *) arg); pthread_mutex_lock( &mutex ); while ( myid != token) { pthread_cond_wait( &cond, &mutex ); } value = value + (myid + 3); printf( "red: id %d \n", value); token = (token + 1) % 3; pthread_cond_broadcast( &cond ); pthread_mutex_unlock( &mutex ); } void * blue ( void *arg ) { int myid = * ((int *) arg); pthread_mutex_lock( &mutex ); while ( myid != token) { pthread_cond_wait( &cond, &mutex ); } value = value * (myid + 2); printf( "blue: id %d \n", value); token = (token + 1) % 3; pthread_cond_broadcast( &cond ); pthread_mutex_unlock( &mutex ); } void * white ( void *arg ) { int myid = * ((int *) arg); pthread_mutex_lock( &mutex ); while ( myid != token) { pthread_cond_wait( &cond, &mutex ); } value = value * (myid + 1); printf( "white: id %d \n", value); token = (token + 1) % 3; pthread_cond_broadcast( &cond ); pthread_mutex_unlock( &mutex ); } main( int argc, char *argv[] ) { pthread_t tid; int count = 0; int id1, id2, id3; id1 = count; n = pthread_create( &tid, null, red, &id1); id2 = ++count; n = pthread_create( &tid, null, blue, &id2); id3 = ++count; n = pthread_create( &tid, null, white, &id3); if ( n = pthread_join( tid, null ) ) { fprintf( stderr, "pthread_join: %s\n", strerror( n ) ); exit( 1 ); } }
i looking comments , or notes output be. exam , offered example. not homework or going used type of submission. looking understand going on. appreciated.
i'm going assume know function of locks, condition variables, , waits. have 3 threads each call red, blue, , white. token 2, , value 3.
red called when id1 = 0, stay in while block calling wait() until token = 0.
blue called when id3 = 1, , stay in while block called wait() until token 1.
white called when id2 = 2, , stay in while block calling wait() until token 2.
so white enter critical section first, since it's 1 won't enter while loop. value = 3 * ( 3 ) = 9; token = ( 3 ) % 3 = 0;
broadcast wakes every waiting thread, 1 enter critical section red. adds 3 value 12; token = ( 1 ) % 3 = 1; broadcast wakes blue.
blue enters critical section. value = 12 * 3; token = 2 ( doesn't matter anymore ).
this order of threads execute, assume test asking. however, should come out just:
white 9
this because there 1 pthread_t tid. after pthread_join( tid, null ), can exit. if put different pthread_t in each of pthread_create() of them print.
Comments
Post a Comment