linux ptheard 生产者消费者

王朝学院·作者佚名  2016-05-26
窄屏简体版  字體: |||超大  

linux ptheard 生产者消费者1#include<stdio.h>2#include<stdlib.h>3#include<pthread.h>45pthread_mutex_tmutex;6pthread_cond_tcond_full;7pthread_cond_tcond_empty;89intg_iBufSize=0;1011void*thread_PRoducer(void*arg)12{13while(true)14{15printf("thread_producer:pthread_mutex_lock\n");16pthread_mutex_lock(&mutex);17//拿到lock就可以访问,不会冲突,但是不一定满足条件,cond是为了在满足条件的时候通知另一个进程18if(0!=g_iBufSize)//如果条件不满足就调用wait函数等待条件满足19{20printf("thread_producer:pthread_cond_waitcond_empty\n");21pthread_cond_wait(&cond_empty,&mutex);//这句话的前提是先有锁,这时候会自动先解锁,等到时机来临在加锁22}2324//前面的wait操作已经包含了枷锁,这里直接访问25printf("thread_producer>>>>>\n");26g_iBufSize=1;2728printf("thread_producer:pthread_cond_signal\n");29pthread_cond_signal(&cond_full);3031pthread_mutex_unlock(&mutex);32}33returnNULL;34}3536void*thread_consumer(void*arg)37{38while(true)39{40printf("thread_consumer:pthread_mutex_lock\n");41pthread_mutex_lock(&mutex);42if(0==g_iBufSize)43{44printf("thread_consumer:pthread_cond_wait\n");45pthread_cond_wait(&cond_full,&mutex);46}4748printf("thread_consumer>>>\n");49g_iBufSize=0;5051printf("thread_consumer:pthread_cond_signal\n");52pthread_cond_signal(&cond_empty);5354pthread_mutex_unlock(&mutex);5556}57returnNULL;58}5960//g++-obin1-lpthreadmutithread.cpp6162intmain()63{64void*retval1,*retval2;65pthread_tthread_id_1,thread_id_2;6667pthread_mutex_init(&mutex,NULL);68pthread_cond_init(&cond_full,NULL);69pthread_cond_init(&cond_empty,NULL);7071pthread_cond_signal(&cond_empty);72pthread_create(&thread_id_1,NULL,thread_producer,NULL);//intpthread_create(pthread_t*tidp,constpthread_attr_t*attr,(void*)(*start_rtn)(void*),void*arg);73pthread_create(&thread_id_2,NULL,thread_consumer,NULL);7475pthread_join(thread_id_1,&retval1);//阻塞等线程执行完76pthread_join(thread_id_2,&retval2);7778pthread_cond_destroy(&cond_full);79pthread_cond_destroy(&cond_empty);80pthread_mutex_destroy(&mutex);8182return0;83}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航