新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
[Linux線程]線程的同步--使用條件變量完成線程同步-創(chuàng)新互聯(lián)
#include#include #define BUFFER_SIZE 4 #define OVER (-1) struct producers //定義生產(chǎn)者條件變量結(jié)構(gòu)。 { int buffer[BUFFER_SIZE]; //定義緩沖區(qū)。 pthread_mutex_t lock; //定義訪問緩沖區(qū)的互斥鎖。 int readpos, writepos; //讀寫的位置。 pthread_cond_t notempty; //緩沖區(qū)有數(shù)據(jù)時(shí)的標(biāo)記。 pthread_cond_t notfull; //緩沖區(qū)未滿的標(biāo)記。 }; //初始化緩沖區(qū) void init(struct producers *b) { pthread_mutex_init(&b->lock,NULL); pthread_cond_init(&b->notempty,NULL); pthread_cond_init(&b->notfull,NULL); b->readpos=0; b->writepos=0; } //在緩沖區(qū)中存放一個(gè)整數(shù)。 void put(struct producers *b, int data) { pthread_mutex_lock(&b->lock); //當(dāng)緩沖區(qū)為滿時(shí)等待。 while((b->writepos+1)%BUFFER_SIZE == b->readpos) { pthread_cond_wait(&b->notfull,&b->lock); //在返回之前,pthread_cond_wait需要參數(shù)b->lock。 } //向緩沖區(qū)中寫數(shù)據(jù),并將寫指針向前移動。 b->buffer[b->writepos] = data; b->writepos++; if(b->writepos >= BUFFER_SIZE) { b->writepos=0; } //發(fā)送當(dāng)前緩沖區(qū)中有數(shù)據(jù)的信號。 pthread_cond_signal(&b->notempty); pthread_mutex_unlock(&b->lock); } //從緩沖區(qū)中讀數(shù)據(jù)并將數(shù)據(jù)從緩沖區(qū)中移走。 int get(struct producers *b) { int data; pthread_mutex_lock(&b->lock); //當(dāng)緩沖區(qū)中有數(shù)據(jù)時(shí)等待。 while(b->writepos == b->readpos) { pthread_cond_wait(&b->notempty,&b->lock); } //從緩沖區(qū)中讀數(shù)據(jù),并將指針前移。 data = b->buffer[b->readpos]; b->readpos++; if(b->readpos >= BUFFER_SIZE) { b->readpos = 0; } //發(fā)送當(dāng)前緩沖區(qū)未滿的信號。 pthread_cond_signal(&b->notfull); pthread_mutex_unlock(&b->lock); return data; } struct producers buffer; //這是生產(chǎn)者的線程處理函數(shù) void *producer(void *data) { int n; for(n=0;n<10;n++) { printf("生產(chǎn)者: %d-->\n",n); //連續(xù)10次生產(chǎn) put(&buffer,n); } put(&buffer,OVER); //將狀態(tài)放入buffer中 return NULL; } //這是消費(fèi)者的線程處理函數(shù) void *consumer(void *data) { int d; while(1) { d = get(&buffer); //從buffer中讀取對應(yīng)的狀態(tài) if(d == OVER) //如果已經(jīng)沒有了則停止 { break; } printf("消費(fèi)者: --> %d\n",d); } return NULL; } //這是主程序 int main(int argc,char *argv[]) { pthread_t thproducer,thconsumer; //生產(chǎn)者和消費(fèi)者的id void *retval; init(&buffer); //初始化緩沖區(qū) pthread_create(&thproducer,NULL,producer,0); pthread_create(&thconsumer,NULL,consumer,0); //創(chuàng)建兩個(gè)線程 pthread_join(thproducer,&retval); pthread_join(thconsumer,&retval); //阻塞進(jìn)程 return 0; }
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
當(dāng)前名稱:[Linux線程]線程的同步--使用條件變量完成線程同步-創(chuàng)新互聯(lián)
標(biāo)題網(wǎng)址:http://www.dlmjj.cn/article/jopsi.html