当前位置:网站首页>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;
}
运行结果

边栏推荐
猜你喜欢

基于激励的需求响应计划下弹性微电网的短期可靠性和经济性评估(Matlab代码实现)

力扣学习---0804

网页端IM即时通讯开发:短轮询、长轮询、SSE、WebSocket

curl命令的那些事

After EasyCVR is locally connected to the national standard device to map the public network, the local device cannot play and cascade the solution

Day018 继承

PHP代码审计8—SSRF 漏洞

八猴渲染器是什么?它能干什么?八猴软件的界面讲解

开发那些事儿:如何通过EasyCVR平台获取监控现场的人流量统计数据?

LVS+NAT 负载均衡群集,NAT模式部署
随机推荐
PHP代码审计7—文件上传漏洞
火灾报警联网FC18中CAN光端机常见问题解答和使用指导
"No title"
用Excel绘制统计图
智能视频监控平台EasyCVR如何使用接口批量导出iframe地址?
阿里云技术专家秦隆:云上如何进行混沌工程?
斯坦福:未来的RGB LED可以贴在你的皮肤上
基于 eBPF 的 Kubernetes 可观测实践
Day018 继承
【RTOS训练营】关于上课和答疑
2022 May 1 Mathematical Modeling Question C Explanation
golang安装和基础配置
ATF中断处理的设计模型
图解LeetCode——899. 有序队列(难度:困难)
【注册荣耀开发者】赢【荣耀70】手机
数据集成:holo数据同步至redis。redis必须是集群模式?
22/8/4 记忆化搜索+博弈论
如何让 JS 代码不可断点
LVS+NAT 负载均衡群集,NAT模式部署
LVS+Keepalived群集