日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

多线程生产者和消费者

發(fā)布時(shí)間:2024/9/30 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 多线程生产者和消费者 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <semaphore.h> #include <unistd.h> #include <iostream>using namespace std;const int ConsumerNum = 3; const int PruducterNum = 2;const int M = 20;//緩存區(qū)大小int in = 0; int out = 0;int buff[M] = {0};sem_t empty_sem;//表示空位的數(shù)量 sem_t full_sem;//產(chǎn)品的數(shù)量pthread_mutex_t mutex;//線程在讀取或產(chǎn)生時(shí),都應(yīng)該加鎖 int i=0;//產(chǎn)品Idvoid *product(void *) {while (true){//sleep(1);sem_wait(&empty_sem);//空位數(shù)減1,已經(jīng)把這個(gè)位置站住了,其他線程只能訪問剩余位置pthread_mutex_lock(&mutex);cout<<"producter "<<pthread_self()<<" produce "<<i<<endl;buff[in] = i++;in = (in+1)%M;pthread_mutex_unlock(&mutex);sem_post(&full_sem);//產(chǎn)品數(shù)加1} }void *consumer(void *) {while(true){//sleep(1);sem_wait(&full_sem);pthread_mutex_lock(&mutex);cout<<"consumer "<<pthread_self()<<" consume "<<buff[out]<<endl;out = (out+1)%M;pthread_mutex_unlock(&mutex);sem_post(&empty_sem);} }int main(void) {pthread_t consumers[ConsumerNum];pthread_t producters[PruducterNum];sem_init(&empty_sem,0,M);//設(shè)初始值為Msem_init(&full_sem,0,0);//初始值為0pthread_mutex_init(&mutex,NULL);for (int ind=0;ind<ConsumerNum;++ind){pthread_create(&consumers[ind],NULL,consumer,(void *)NULL);}for (int ind=0;ind<PruducterNum;++ind){pthread_create(&producters[ind],NULL,product,(void *)NULL);}for(int ind =0;ind<ConsumerNum;++ind)pthread_join(consumers[ind],NULL);for(int ind = 0;ind <PruducterNum;++ind)pthread_join(producters[ind],NULL);exit(0); }



總結(jié)

以上是生活随笔為你收集整理的多线程生产者和消费者的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。