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