当前位置:网站首页>作业8.3 线程同步互斥机制条件变量
作业8.3 线程同步互斥机制条件变量
2022-08-04 18:24:00 【不知名大学生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>
//定义三个条件变量
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[])
{
//创建三个条件变量
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("创建条件变量成功\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;
}
运行结果

边栏推荐
猜你喜欢

ptables基本语法使用规则

YOLOv7-Pose尝鲜,基于YOLOv7的关键点模型测评

路由技术

使用.NET简单实现一个Redis的高性能克隆版(二)

Create Sentinel high-availability cluster current limiting middleware from -99

企业即时通讯软件有哪些功能?对企业有什么帮助?

"No title"

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

Hezhou Cat1 4G module Air724UG is configured with RNDIS network card or PPP dial-up, and the development board is connected to the Internet through the RNDIS network card (taking the RV1126/1109 devel

12. SAP ABAP OData 服务如何支持 $select 有选择性地仅读取部分模型字段值
随机推荐
Go 言 Go 语,一文看懂 Go 语言文件操作
Global electronics demand slows: Samsung's Vietnam plant significantly reduces capacity
如何进行自动化测试?
基于 eBPF 的 Kubernetes 可观测实践
EasyCVR本地接入国标设备映射公网后,本地设备出现无法播放与级联的解决方法
buuctf(探险1)
关于使用腾讯云HiFlow场景连接器每天提醒签到打卡
如何封装 svg
mq消息积压怎么对应
How to make JS code unbreakable
斯坦福:未来的RGB LED可以贴在你的皮肤上
LVS负载均衡群集之原理叙述
powershell和cmd对比
#yyds干货盘点# 面试必刷TOP101:链表相加(二)
路由懒加载
当项目中自动格式化插件Prettier和ESLint冲突报错时如何解决
Enterprise survey correlation analysis case
CAN光纤转换器CAN光端机解决消防火灾报警
通俗易懂-二维数组只能省略行不能省略列-人话版本
【填空题】130道面试填空题