linux|linux 10 次顺序打印ABC

#include
#include

#define TIMES 10
int condition = 'A';
pthread_cond_t condA,condB,condC;
pthread_mutex_t mutex;
void* funA(void* a)
{
int runA =1;
while(true)
{
pthread_mutex_lock(&mutex);
while(condition != 'A')
{
pthread_cond_wait(&condA,&mutex); //wait是做完事情之前等待,是用来等待某一条件
//wait首先操作系统将线程A放到线程等待队列,然后解锁线程。
}
printf("this is fun A %d times\n",runA);
【linux|linux 10 次顺序打印ABC】runA++;
condition = 'B';
pthread_cond_signal(&condB); //通知下一个指定线程
pthread_mutex_unlock(&mutex);
if(runA>10)
pthread_exit(NULL);
}
}
void* funB(void* b)
{
int runB =1;
while(true)
{
pthread_mutex_lock(&mutex);
while(condition != 'B')
{
pthread_cond_wait(&condB,&mutex);
}
printf("this is fun B %d times\n",runB);
runB++;
condition = 'C';
pthread_cond_signal(&condC);
pthread_mutex_unlock(&mutex);
if(runB>10)
pthread_exit(NULL);
}
}
void* funC(void* c)
{
int runC =1;
while(true)
{
pthread_mutex_lock(&mutex);
while(condition != 'C')
{
pthread_cond_wait(&condC,&mutex);
}
printf("this is fun C %d times\n",runC);
runC++;
condition = 'A';
pthread_cond_signal(&condA);
pthread_mutex_unlock(&mutex);
if(runC>10)
pthread_exit(NULL);
}
}
int main(int argc,char** argv)
{
pthread_t pt[3];
pthread_cond_init(&condA,NULL);
pthread_cond_init(&condB,NULL);
pthread_cond_init(&condC,NULL);
pthread_mutex_init(&mutex,NULL);
pthread_create(&pt[0],NULL,funA,NULL);
pthread_create(&pt[1],NULL,funB,NULL);
pthread_create(&pt[2],NULL,funC,NULL);
pthread_join(pt[0],NULL);
pthread_join(pt[1],NULL);
pthread_join(pt[2],NULL);
pthread_cond_destroy(&condA);
pthread_cond_destroy(&condB);
pthread_cond_destroy(&condC);
pthread_mutex_destroy(&mutex);
return 0;
}
注:下一篇的pthread_cond_wait和pthread_mutex_lock文章中会有对本篇内容的补充跟深入理解。

    推荐阅读