基于条件变量和互斥量同步的三线程顺序打印abc(10次)实现
来源:互联网 发布:制作动态原理图软件 编辑:程序博客网 时间:2024/06/10 11:05
先看代码
//创建三个线程顺序打印abc//利用条件变量加互斥量实现//#include<stdio.h>#include<stdlib.h>#include<sys/types.h>#include<unistd.h>#include<pthread.h>//线程相关的头文件int i=0;int n=0;//声明互斥量,条件变量pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;pthread_cond_t cond=PTHREAD_COND_INITIALIZER;void* printa(){while(n<10){pthread_mutex_lock(&mutex);while(i!=1)pthread_cond_wait(&cond,&mutex);pthread_t tid;tid=pthread_self();printf("a tid:%lu\n",tid);i++;pthread_mutex_unlock(&mutex);sleep(1);}return (void *)0;}void* printb(){while(n<10){pthread_mutex_lock(&mutex);while(i!=2)pthread_cond_wait(&cond,&mutex);pthread_t tid;tid=pthread_self();printf("b tid:%lu\n",tid);i++;pthread_mutex_unlock(&mutex);}return (void *)0;}void* printc(){while(n<10){pthread_mutex_lock(&mutex);while(i!=3)pthread_cond_wait(&cond,&mutex);pthread_t tid;tid=pthread_self();printf("c tid:%lu\n",tid);i=1;n++;sleep(1);pthread_mutex_unlock(&mutex);printf("\n");}return (void *)0;}int main(){pthread_t tid;int err;err=pthread_create(&tid,NULL,printa,NULL);if(err!=0)printf("pthread_creat erro\n");err=pthread_create(&tid,NULL,printb,NULL);if(err!=0)printf("pthread_creat erro\n");err=pthread_create(&tid,NULL,printc,NULL);if(err!=0)printf("pthread_creat erro\n");pthread_mutex_lock(&mutex);i++;pthread_mutex_unlock(&mutex);while(1){if(i==1||i==2||i==3)pthread_cond_broadcast(&cond);if(n==10)break;}exit(0);}
条件变量决定线程是否输出,互斥量保护对条件。需要解释的是pthread_cond_wait()传入的参数是锁着的互斥量和条件,函数内部会对互斥量进行解锁,这样其他线程申请互斥量加锁的操作可以成功,3个线程都会停留在while(条件)这里。最后注意记得pthread_cond_broadcast(&cond);
0 0
- 基于条件变量和互斥量同步的三线程顺序打印abc(10次)实现
- 多线程(至少三个线程)分别打印A、B、C,要求按ABC的顺序循环打印10次。
- 3个线程每个线程只能打印自己的名字,在屏幕上顺序打印 ABC,打印10次
- Java三线程按序打印10次ABC (Lock实现与synchronized,wait,notify实现)
- 启动三个线程A,B,C,打印10次 按照ABC的顺序输出
- 多线程同步 顺序打印数字 线程条件变量
- 多线程题 3个线程各打印一种字母,按顺序打印若干次ABC 的2种实现
- 三个线程轮流执行顺序打印ABC(三):使用Lock实现
- VC 三线程顺序打印ABC
- 多线程顺序打印ABC的三种实现---join方法
- 一道Java线程面试题。3个线程顺序打印10次ABC.
- 有三个线程名字分别是A、B、C,每个线程只能打印自己的名字,在屏幕上顺序打印 ABC,打印10次。
- 线程顺序打印ABC
- linux线程同步:互斥量和条件变量的使用
- 菜鸟更要独立思考之二 改进一个不使用wait和notify顺序打印ABC 10次的算法
- 多线程之三个ABC线程实现循环打印100次
- 线程的同步--条件变量
- 三个线程顺序打印ABC
- 结构体struct的sizeof
- pthread_join和pthread_detach的区别
- ecshop 在商品列表页添加类似于精品、热销的功能
- 配置Log4j
- 配Android环境
- 基于条件变量和互斥量同步的三线程顺序打印abc(10次)实现
- was 自启脚本
- 贝塞尔曲线扫盲
- Crashlytics——iOS crash log 解析利器
- 美国威布森碳纤维电地暖 电能转换为热能采暖节能更舒适
- HTML&CSS Learning Notes 4
- WIFI基本知识整理
- Netty源码学习(一)----概述
- android获取指定路径下目录文件