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 is %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 is %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 is %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 );
}
}
我只是在寻找关于输出内容的评论和/或注释。这是为了考试而提供的。这不是家庭作业,也不会用于任何类型的提交。我希望了解发生了什么。任何帮助是极大的赞赏。