c++信号量实现生产者消费者模型

c++信号量实现生产者消费者模型,第1张

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

//int empty_slot = 5;
//int filled_slot = 0;
sem_t empty_slot;
sem_t filled_slot;
sem_t locked;
vector<int> num;


void *producer(void *arg){
    while(1){
        sem_wait(&empty_slot);
        sem_wait(&locked);
        int data = rand()%10;
        num.push_back(data);
        int len = num.size();
        cout<<"producer:";
        for(int i=0; i<len; i++){
            cout<<num[i]<<" ";
        }
        cout<<endl;
        sem_post(&filled_slot);
        sem_post(&locked);
    }
    

}

void *consumer(void *arg){
    while(1){
        sem_wait(&filled_slot);
        sem_wait(&locked);
        int m = num.back();
        num.pop_back();
        int len = num.size();
        cout<<"consumer:";
        cout<<m<<" ";
        cout<<endl;
        sem_post(&empty_slot);
        sem_post(&locked);
    }
    
}

int main(){
    pthread_t tid1, tid2;
    sem_init(&empty_slot,0, 5);
    sem_init(&filled_slot,0, 0);
    sem_init(&locked,0, 1);

    
    pthread_create(&tid2,NULL,consumer,NULL);
    pthread_create(&tid1,NULL,producer, NULL);

    //等待线程结束
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);

    sem_destroy(&empty_slot);
    sem_destroy(&filled_slot);
    sem_destroy(&locked);
    

    return 0;

}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/634949.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-16
下一篇 2022-04-16

发表评论

登录后才能评论

评论列表(0条)

保存