UNIX环境高级编程:线程同步之条件变量及属性
发布时间:2016-07-28 15:45:36 所属栏目:Unix 来源:站长网
导读:条件变量变量也是出自POSIX线程标准,另一种线程同步机制。主要用来等待某个条件的发生。可以用来同步同一进程中的各个线程。当然如果一个条件变量存放在多个进
示例代码: #include <stdio.h> #include <pthread.h> #include <unistd.h> pthread_mutex_t count_lock; pthread_cond_t count_nonzero; unsigned count = 0; void *decrement_count(void *arg) { pthread_mutex_lock(&count_lock); printf("decrement_count get count_lockn"); while(count == 0) { printf("decrement_count count == 0 n"); printf("decrement_count before cond_wait n"); pthread_cond_wait(&count_nonzero, &count_lock); printf("decrement_count after cond_wait n"); printf("decrement_count count = %d n",count); } count = count + 1; pthread_mutex_unlock(&count_lock); } void *increment_count(void *arg) { pthread_mutex_lock(&count_lock); printf("increment_count get count_lock n"); if(count == 0) { printf("increment_count before cond_signal n"); pthread_cond_signal(&count_nonzero); printf("increment_count after cond_signal n"); } count = count + 1; printf("huangcheng n"); printf("increment_count count = %d n",count); pthread_mutex_unlock(&count_lock); } int main(void) { pthread_t tid1, tid2; pthread_mutex_init(&count_lock, NULL); pthread_cond_init(&count_nonzero, NULL); pthread_create(&tid1, NULL, decrement_count, NULL); sleep(2); pthread_create(&tid2, NULL, increment_count, NULL); sleep(10); pthread_exit(0); return 0; } 查看本栏目更多精彩内容:http://www.bianceng.cn/OS/unix/ (编辑:源码网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |