即将进行的有关pthread的考试的示例代码输出

时间:2013-05-13 20:18:55

标签: pthreads conditional mutex

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 ); 
 } 
}

我只是在寻找关于输出的评论和/或注释。这是一个考试,并作为一个例子提供。这不是家庭作业或将用于任何类型的提交。我希望了解发生了什么。任何帮助是极大的赞赏。

1 个答案:

答案 0 :(得分:0)

我将假设你知道锁,条件变量和等待的功能。基本上你有三个线程,每个线程调用红色,蓝色和白色。令牌最初为2,值最初为3。

当id1 = 0时调用Red,但它将保持在while块中调用wait()直到令牌= 0.

当id3 = 1时调用Blue,并且将保持在名为wait()的while块中,直到令牌为1.

当id2 = 2时调用White,并且将在while块中调用wait(),直到令牌为2。

所以White将首先进入临界区,因为它是唯一不会进入while循环的区域。所以value = 3 *(3)= 9; token =(3)%3 = 0;

广播唤醒每个等待的线程,但唯一进入临界区的是红色。它增加3到12的值; token =(1)%3 = 1;广播唤醒蓝色。

蓝色进入关键部分。值= 12 * 3;令牌= 2(但不再重要)。

这将是线程执行的顺序,这是我认为测试真正要求的。但是,真正应该出现的只是:

白色是9

这是因为只有一个pthread_t tid。所以在pthread_join(tid,NULL)之后,它可以立即退出。如果你在每个pthread_create()中放入不同的pthread_t,那么它们都会打印出来。