#include<stdio.h>#include<pthread.h>#include<unistd.h>//创建条件变量pthread_cond_t cond;//创建互斥锁pthread_mutex_t mutex;//线程处理函数1void *threadfun1(void *arg){ char* name = (char*)arg; while(1) { pthread_mutex_lock(&mutex); pthread_cond_wait(&cond,&mutex); printf("%s is waked up...\n",name); sleep(1); pthread_mutex_unlock(&mutex); } }//线程处理函数2void *threadfun2(void *arg){ char *name = (char *)arg; while(1) { sleep(1); //唤醒一个等待队列中的线程 pthread_cond_signal(&cond); printf("%s is wakeding up a thread...\n",name); }}int main(){ pthread_t pthread1,pthread2,pthread3,pthread4,pthread5; //初始化条件变量 pthread_cond_init(&cond,NULL); //初始化互斥锁 pthread_mutex_init(&mutex,NULL); //创建五个线程 pthread_create(&pthread1,NULL,threadfun1,(void *)"pthread 1"); pthread_create(&pthread2,NULL,threadfun1,(void *)"pthread 2"); pthread_create(&pthread3,NULL,threadfun1,(void *)"pthread 3"); pthread_create(&pthread4,NULL,threadfun1,(void *)"pthread 4"); pthread_create(&pthread5,NULL,threadfun2,(void *)"pthread 5");//等待线程结束 pthread_join(pthread1,NULL); pthread_join(pthread2,NULL); pthread_join(pthread3,NULL); pthread_join(pthread4,NULL); pthread_join(pthread5,NULL); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); return 0;}运行结果如下:
![二 Linux--多线程](http://img.zhejianglong.com/231019/051649EZ-5.png)
文章插图
值得注意的是pthread_cond_wait在阻塞的时候,会释放已经掌握的互斥锁,等到被唤醒的时候,重新上锁 。
举个例子:
![二 Linux--多线程](http://img.zhejianglong.com/231019/0516491141-6.png)
文章插图
其实pthread_cond_wait内部隐藏一次解锁的过程,如果是fun1先运行,num被上锁,会阻塞在第24条语句,但是pthread_cond_wait会先解锁,释放掉num资源,但依然阻塞在24行 , 此时fun2加锁,改变条件,函数pthread_cond_signal会唤醒pthread_cond_wait函数,此时num会再次被上锁,然后解锁,所以pthread_cond_wait其实在内部做了一次解锁的操作 。
条件变量其实很简单,遇到pthread_cond_wait线程就会阻塞在阻塞队列 , 当pthread_cond_signal调用的时候,就会唤醒在阻塞队列中的线程,继续执行下面的代码 。
【二 Linux--多线程】
推荐阅读
- 华为watch3可以使用微信吗_华为watch3有微信吗
- Python 多重继承时metaclass conflict问题解决与原理探究
- 神仙记事录第十二章怎么过
- 嘉峪关到张掖-嘉峪关到张掖多少公里
- 多玩LOL盒子战绩查询 英雄联盟战绩查询在线查询系统
- dnf公会勋章怎么获得(dnf公会传说勋章多久能获得)
- 【多服务场景化解决方案】AR虚拟技术助力智能家装
- 一 Linux--多线程
- pta第二次博客
- 1斤等于多少磅 一斤等于多少磅