编写一个程序,开启
3
个 线程,这
3
个线程的
ID
分别为
ABC
,每个线程将自己的
ID
在屏幕上打印
10
遍,要求输出结果必须按
ABC
的顺序显示,如
ABCABC……
依次递推;
提示:
A
只能叫醒
B
,
B
只能唤醒
C
,
C
只能唤醒
A
;
#include <stdio.h>
#include <pthread.h>
pthread_cond_t cond; //条件变量
pthread_mutex_t mutex; //互斥锁
int flag = 0; //标志,0:打印 A, 1:打印 B, 2:打印 C
int count = 0;
void* A(void* arg)
{
while(1)
{
if(count == 10) //打印10次后退出进程
{
pthread_exit(NULL);
}
pthread_mutex_lock(&mutex);//上锁
if(flag == 0) //flag为0打印A
{
printf("A");
flag = 1; //打印完后,flag置1,准备打印B
}else //flag不为0,线程休眠
{
pthread_cond_wait(&cond,&mutex);
}
pthread_mutex_unlock(&mutex); //解锁
pthread_cond_signal(&cond); //唤醒
}
}
void* B(void* arg)
{
while(1)
{
if(count == 10) //打印10次后退出进程
{
pthread_exit(NULL);
}
pthread_mutex_lock(&mutex);//上锁
if(flag == 1) //flag为1打印B
{
printf("B");
flag = 2; //打印完后,flag置2,准备打印C
}else //flag不为1,线程休眠
{
pthread_cond_wait(&cond,&mutex);
}
pthread_mutex_unlock(&mutex); //解锁
pthread_cond_signal(&cond); //唤醒
}
}
void* C(void* arg)
{
while(1)
{
if(count == 10) //打印10次后退出进程
{
printf("\n");
pthread_exit(NULL);
}
pthread_mutex_lock(&mutex);//上锁
if(flag == 2) //flag为2打印C
{
printf("C");
flag = 0; //打印完后,flag置0,准备打印A
count++; //ABC都打印了一遍
}else //flag不为2,线程休眠
{
pthread_cond_wait(&cond,&mutex);
}
pthread_mutex_unlock(&mutex); //解锁
pthread_cond_signal(&cond); //唤醒
}
}
int main(int argc, const char *argv[])
{
//创建条件变量
if(0 != pthread_cond_init(&cond,NULL))
{
perror("pthread_cond_init");
return -1;
}
//创建互斥锁
if(0 != pthread_mutex_init(&mutex,NULL))
{
perror("pthread_mutex_init");
return -1;
}
//打开三个线程
pthread_t pth1,pth2, pth3;
if(0 != pthread_create(&pth1, NULL, A, NULL))
{
perror("pthread_create");
return -1;
}
if(0 != pthread_create(&pth2, NULL, B, NULL))
{
perror("pthread_create");
return -1;
}
if(0 != pthread_create(&pth3, NULL, C, NULL))
{
perror("pthread_create");
return -1;
}
//阻塞,等待回收进程资源
pthread_join(pth1, NULL);
pthread_join(pth2, NULL);
pthread_join(pth3, NULL);
//销毁互斥锁
pthread_mutex_destroy(&mutex);
//销毁条件变量
pthread_cond_destroy(&cond);
return 0;
}
结果:
ubuntu@ubuntu:day6$ ./a.out
ABCABCABCABCABCABCABCABCABCABC