C++ pthread cond_wait 和 cond_broadcast的使用
来源:互联网 发布:微博发长图用什么软件 编辑:程序博客网 时间:2024/06/08 06:13
一个简单的实例程序,说明pthread_cond_wait 和 pthread_cond_broadcast 的使用方式。
函数定义:
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
int pthread_cond_broadcast(pthread_cond_t *cond)
函数说明:
pthread_cond_wait :有两个输入参数,一个是pthread_cond_t,是函数将要等待的信号,另一个是 pthread_mutex_t,一个互斥锁。用于对信号量进行保护,防止多个线程同时对其进行操作。在线程开始等待信号量前,必须由本线程对互斥锁进行锁定,然后pthread_cond_wait会更新条件等待队列,并且释放互斥量,允许其他线程进行访问;当cond 满足条件允许线程继续执行时,wait_cond也会先对mutex 进行锁定,对cond进行处理,然后再允许线程继续运行。所以pthread_cond_wait() 后的pthread_mutex_unlock()还是必要的。
实例程序:
#include <pthread.h>#include <iostream>#include <unistd.h>using namespace std; static pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER;static pthread_cond_t cond=PTHREAD_COND_INITIALIZER;static void* func_1(void* arg){ cout << "func_1 start" << endl; pthread_mutex_lock(&mtx); cout << "func_1 lock mtx" << endl; cout << "func_1 wait cond" << endl; pthread_cond_wait(&cond, &mtx); cout << "func_1 unlock mtx" << endl; pthread_mutex_unlock(&mtx); cout << "func_1 end" << endl; sleep(5); return NULL;}static void* func_2(void* arg){ cout << "func_2 start" << endl; pthread_mutex_lock(&mtx); cout << "func_2 lock mtx" << endl; cout << "func_2 wait cond" << endl; pthread_cond_wait(&cond, &mtx); cout << "func_2 unlock mtx" << endl; pthread_mutex_unlock(&mtx); cout << "func_2 end" << endl; sleep(5); return NULL;}int main(){ pthread_t tid1, tid2; cout << "main create thread" << endl; pthread_create(&tid1, NULL, func_1, NULL); pthread_create(&tid2, NULL, func_2, NULL); sleep(3); cout << "main boradcast signal" << endl; pthread_cond_broadcast(&cond); cout << "main join thread" << endl; pthread_join(tid1, NULL); pthread_join(tid2, NULL); cout << "main end" << endl; return 0;}
测试结果:
1 0
- C++ pthread cond_wait 和 cond_broadcast的使用
- C语言 pthread的使用
- C语言 Pthread的学习使用
- pthread和std::thread中条件变量的使用
- 网络多线程-pthread的使用
- [C++]pthread
- [C/C++]_[初级]_[ 线程pthread学习之互斥锁和条件变量的应用 ]
- VS2012下安装和使用Pthread
- Cocos2dx中使用socket、json和pthread
- Eclipse 使用C++类库:pthread和openssl
- pthread使用
- pthread使用
- Dev_c++下解决编译winsock和pthread 的链接问题C++&STL
- [并发并行]_[C/C++]_[使用线程本地存储Thread Local Storage(TLS)-win32线程和pthread线程比较]
- g++的-pthread和-lpthread的区别
- C++中使用pthread的策略
- pthread条件变量函数的使用
- pthread-win32在VC2005下的使用
- vtk filter 的写法
- DFS所用到的奇偶剪枝
- poj1083 思维题
- [Leetcode] 14. Longest Common Prefix
- 实用数据结构---图的操作和算法
- C++ pthread cond_wait 和 cond_broadcast的使用
- matlab数组中求最大的几个数并返回其位置
- 安装visul studio 2010或2008失败的解决方案
- Linux Tar Command
- Java中静态变量与实例变量的区别
- 整数数字之和
- 出现错误“tcnative-1.dll: Can't load AMD 64-bit .dll on a IA 32-bit platform”的解决办法
- android阿拉伯语言的数字
- 最大乘积 Uva 11059