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

#include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>
#include <semaphore.h>
#include <vector>
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;

}
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值