进程同步——生产者消费者问题

  1. 使用高级编程语言实现生产者消费者问题,生产者需要持续的在缓冲区中写入数据,消费者持续的从缓冲区中读取数据。互斥的建立生产者操作和消费者操作,同一时刻只能有一个进程对缓冲区操作。
  2. 生产者首先要查看缓冲区是否已满。如果缓冲区已满,那么需要等待消费者进程读取数据。消费者进程需要判断缓冲区是否为空。如果缓冲区为空,那么需要等待生产者进程写入数据。
    c++

#include <iostream>
#include<mutex>
#include <thread>
#include<condition_variable>
using namespace std;
int ziYuan[5]={0};
int ind=1,nu=0,sc=1,xf=1;
#define MAX 5
mutex mutex0;
unique_lock<mutex> mu(mutex0,defer_lock);
condition_variable cond;

void prints()
{
    for(int i=0;i<MAX;i++)
    {
        cout<<i<<": "<<ziYuan[i];
        if(ziYuan[i]==sc)cout<<"<----produce  ";
        if(ziYuan[i]==xf)cout<<"<----consume  ";
        cout<<"\n";
    }
}

void ShengChan()
{
    while(1)
    {
        mu.lock();
        if(nu>=MAX)
        {
            mu.unlock();
            cond.notify_one();
            continue;
        }
        nu++;
        ziYuan[sc%MAX]=sc;
        cout<<"produce:   "<<sc<<endl;
        prints();
        sc++;
        this_thread::sleep_for(1s);
        cond.notify_one();
        mu.unlock();
    }
}
void XiaoFei()
{
    while(1)
    {
        cond.wait(mu);
        if(nu==0)
        {
            mu.unlock();
            continue;
        }
        xf++;
        cout<<"consume   "<<xf<<endl;
        nu--;
        ziYuan[xf%MAX]=xf;
        prints();
        xf++;
        this_thread::sleep_for(1s);

    }
}
int main() {
    thread tShengchan(ShengChan);
    thread tXiaoFei(XiaoFei);
    tShengchan.join();
    tXiaoFei.join();
    return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值