ccx_wz的ChinaUnix博客chencaixiong.blog.chinaunix.net
ccx_wz
全部博文(489)
2013年(7)
2012年(301)
2011年(181)
jiuniu11
liangsto
sh365
dyli2000
CU官方博
y3079214
smsong_c
rubik_ns
guoxiaor
wb123456
cynthia
浪花小雨
Bsolar
178919
tomcodin
UMK_eRai
linux_ss
分类:
2011-12-22 20:50:31
原文地址:线程同步(条件变量) 作者:luozhiyong131
#include <stdio.h>#include <stdlib.h>#include <pthread.h>pthread_mutex_t mutex;pthread_cond_t cond;int x;void consumer(void){while(1){pthread_mutex_lock(&mutex);int i;while(x<3){pthread_cond_wait(&cond,&mutex);printf("start consumingn",x);}while(x>0){x--;printf("consuming x=%dn",x);sleep(1);}pthread_mutex_unlock(&mutex); }pthread_exit(NULL);}void producer(void){while(1){pthread_mutex_lock(&mutex);int i;for(i=0;i<3-x;i++){x++;printf("produing x=%dn",x);sleep(1);}if(x>=3){pthread_cond_signal(&cond);printf("producing completedn",x);}pthread_mutex_unlock(&mutex);sleep(1);}pthread_exit(NULL);}int main(void){pthread_t id1,id2;int ret;ret = pthread_mutex_init(&mutex,NULL);if(ret!=0){printf("pthread_mutex_init errorn");exit(1);}ret = pthread_cond_init(&cond,NULL);if(ret!=0){printf("pthread_cond_init errorn");exit(1);}ret = pthread_create(&id1,NULL,(void *)&producer,NULL);if(ret!=0){printf("pthread_create producer errorn");exit(1);}ret = pthread_create(&id2,NULL,(void *)&consumer,NULL);if(ret!=0){printf("pthread_create consumer errorn");exit(1);}pthread_join(id1,NULL);pthread_join(id2,NULL);return 0;}
上一篇:LED
下一篇:线程同步——信号量
登录 注册