国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > Linux > 正文

linux ptheard 生產(chǎn)者消費(fèi)者

2024-06-28 13:21:07
字體:
供稿:網(wǎng)友
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}
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 通道| 盘锦市| 平顶山市| 平山县| 阿拉善左旗| 镇安县| 丰镇市| 将乐县| 合阳县| 祁东县| 定西市| 运城市| 无锡市| 潞城市| 吉木萨尔县| 阿拉善盟| 台中市| 景洪市| 昔阳县| 丰都县| 义马市| 宁都县| 曲阜市| 西丰县| 东光县| 吴川市| 千阳县| 潮州市| 申扎县| 延安市| 广饶县| 将乐县| 九龙坡区| 沂南县| 平定县| 乌兰察布市| 方正县| 措美县| 揭西县| 怀集县| 桐柏县|