静态态初始化,pthread_cond_t cond = PTHREAD_COND_INITIALIER;
动态初始化,int pthread_cond_init(pthread_cond_t *cond,pthread_condattr_t *cond_attr);
2、等待条件成立 。释放锁,同时阻塞等待条件变量为真才行 。timewait()设置等待时间,仍未signal,返回ETIMEOUT(加锁保证只有一个线程wait)
int pthread_cond_wait(pthread_cond_t *cond,pthread_mutex_t *mutex);
int pthread_cond_timewait(pthread_cond_t *cond,pthread_mutex *mutex,const timespec *abstime);
4、激活条件变量 。pthread_cond_signal,pthread_cond_broadcast(激活所有等待线程)
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond); //解除所有线程的阻塞
5、清除条件变量 。无线程等待,否则返回EBUSY
int pthread_cond_destroy(pthread_cond_t *cond);
01[cpp] view plain copy02#include 03#include 04#include "stdlib.h"05#include "unistd.h"06pthread_mutex_t mutex;07pthread_cond_t cond;08void hander(void *arg)09{10free(arg);11(void)pthread_mutex_unlock(&mutex);12}13void *thread1(void *arg)14{15pthread_cleanup_push(hander, &mutex);16while(1)17{18printf("thread1 is runningn");19pthread_mutex_lock(&mutex);20pthread_cond_wait(&cond, &mutex);21printf("thread1 applied the conditionn");22pthread_mutex_unlock(&mutex);23sleep(4);24}25pthread_cleanup_pop(0);26}27void *thread2(void *arg)28{29while(1)30{31printf("thread2 is runningn");32pthread_mutex_lock(&mutex);33pthread_cond_wait(&cond, &mutex);34printf("thread2 applied the conditionn");35pthread_mutex_unlock(&mutex);36sleep(1);37}38}39int main()40{41pthread_t thid1,thid2;42printf("condition variable study!n");43pthread_mutex_init(&mutex, NULL);44pthread_cond_init(&cond, NULL);45pthread_create(&thid1, NULL, thread1, NULL);46pthread_create(&thid2, NULL, thread2, NULL);47sleep(1);48do49{50pthread_cond_signal(&cond);51}while(1);52sleep(20);53pthread_exit(0);54return 0;55}复制代码[cpp] view plain copy#include #include #include "stdlib.h"#include "unistd.h"pthread_mutex_t mutex;pthread_cond_t cond;void hander(void *arg){free(arg);(void)pthread_mutex_unlock(&mutex);}void *thread1(void *arg){pthread_cleanup_push(hander, &mutex);while(1){printf("thread1 is runningn");pthread_mutex_lock(&mutex);pthread_cond_wait(&cond, &mutex);printf("thread1 applied the conditionn");pthread_mutex_unlock(&mutex);sleep(4);}pthread_cleanup_pop(0);}void *thread2(void *arg){while(1){printf("thread2 is runningn");pthread_mutex_lock(&mutex);pthread_cond_wait(&cond, &mutex);printf("thread2 applied the conditionn");pthread_mutex_unlock(&mutex);sleep(1);}}int main(){pthread_t thid1,thid2;printf("condition variable study!n");pthread_mutex_init(&mutex, NULL);pthread_cond_init(&cond, NULL);pthread_create(&thid1, NULL, thread1, NULL);pthread_create(&thid2, NULL, thread2, NULL);sleep(1);do{pthread_cond_signal(&cond);}while(1);sleep(20);pthread_exit(0);return 0;}01#include 02#include
推荐阅读
- 淘宝斗地主为什么玩不了
- 纯手工蔬果q丸怎么做
- 萧居棠口中所说的爹爹是谁 楚留香手游11月29日每日一题
- 微信发长图连着的照片教程
- 建行6253开头的是什么卡
- Photoshop调出人物照片粉嫩的淡青色
- 楚留香手游11.29在哪打坐 11月29日坐观万象打坐修炼地点坐标
- biscuit是可数名词吗
- 蔡居诚是被谁坑进点香阁 楚留香手游11月28日每日一题