多线程生产者和消费者
生活随笔
收集整理的這篇文章主要介紹了
多线程生产者和消费者
小編覺得挺不錯(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)容,希望文章能夠幫你解決所遇到的問題。