当前位置:网站首页>Homework 8.3 Thread Synchronization Mutex Condition Variables
Homework 8.3 Thread Synchronization Mutex Condition Variables
2022-08-04 18:33:00 【Unknown college student M】
题目:编写一个程序,开启3个 线程,这3个线程的ID分别为ABC,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示,如ABCABC……依次递推;
提示:A只能叫醒B,B只能唤醒C,C只能唤醒A;
实现代码
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
//Define three condition variables
pthread_cond_t cond1;
pthread_cond_t cond2;
pthread_cond_t cond3;
//互斥锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* A(void* arg)
{
for(int i=0;i<10;i++)
{
pthread_mutex_lock(&mutex);
printf("A");
pthread_cond_signal(&cond2);
pthread_cond_wait(&cond1, &mutex);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void* B(void* arg)
{
for(int i=0;i<10;i++)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond2, &mutex);
printf("B");
pthread_cond_signal(&cond3);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void* C(void* arg)
{
for(int i=0;i<10;i++)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond3, &mutex);
printf("C");
pthread_cond_signal(&cond1);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//Create three condition variables
if(pthread_cond_init(&cond1, NULL) != 0)
{
perror("pthread_cond_init");
return -1;
}
if(pthread_cond_init(&cond2, NULL) != 0)
{
perror("pthread_cond_init");
return -1;
}
if(pthread_cond_init(&cond3, NULL) != 0)
{
perror("pthread_cond_init");
return -1;
}
printf("Condition variable creation succeeded\n");
//创建3个线程
pthread_t tid1,tid2,tid3;
//A线程打印A
if(pthread_create(&tid1,NULL,A,NULL)!=0)
{
perror("pthread_creat");
return -1;
}
//B线程打印B
if(pthread_create(&tid2,NULL,B,NULL)!=0)
{
perror("pthread_creat");
return -1;
}
//C线程打印C
if(pthread_create(&tid3,NULL,C,NULL)!=0)
{
perror("pthread_creat");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
printf("\n");
//销毁互斥锁
pthread_mutex_destroy(&mutex);
//销毁条件变量
pthread_cond_destroy(&cond1);
pthread_cond_destroy(&cond2);
pthread_cond_destroy(&cond3);
return 0;
}
运行结果
边栏推荐
猜你喜欢
随机推荐
单行、多行文本超出显示省略号
PHP代码审计10—命令执行漏洞
localstorage本地存储的方法
After EasyCVR is locally connected to the national standard device to map the public network, the local device cannot play and cascade the solution
机器学习——线性回归
如何给MySQL添加自定义语法 ?
【注册荣耀开发者】赢【荣耀70】手机
实验室专利书写指南
ERC721标准与加密猫
Matlab drawing 1
dotnet core 输出调试信息到 DebugView 软件
用Excel绘制统计图
”元宇宙“必须具备这些特点
谁能解答?从mysql的binlog读取数据到kafka,但是数据类型有Insert,updata,
企业即时通讯软件有哪些功能?对企业有什么帮助?
运力升级助力算力流转,中国数字经济的加速时刻
部署LVS-DR群集
FE01_OneHot-Scala应用
EasyCVR调用云端录像API接口返回错误且无录像文件生成,是什么原因?
Error when using sourcemap for reporting an error: Can‘t resolve original location of error.