linux ptheard 生產(chǎn)者消費(fèi)者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是為了在滿足條件的時(shí)候通知另一個(gè)進(jìn)程18if(0!=g_iBufSize)//如果條件不滿足就調(diào)用wait函數(shù)等待條件滿足19{20printf("thread_producer:pthread_cond_waitcond_empty/n");21pthread_cond_wait(&cond_empty,&mutex);//這句話的前提是先有鎖,這時(shí)候會自動先解鎖,等到時(shí)機(jī)來臨在加鎖22}2324//前面的wait操作已經(jīng)包含了枷鎖,這里直接訪問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);//阻塞等線程執(zhí)行完76pthread_join(thread_id_2,&retval2);7778pthread_cond_destroy(&cond_full);79pthread_cond_destroy(&cond_empty);80pthread_mutex_destroy(&mutex);8182return0;83}