//producer_consumer.cc
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
const int bufferSize = 8;
vector<int> buffer(bufferSize);
queue<int> waitQueue;
int id;
int writeptr, readptr;
int consumer, producer;
void init()
{
for (int i = 0; i < bufferSize; ++i)
{
buffer[i] = 0;
}
while(!waitQueue.empty())
{
waitQueue.pop();
}
id = 0;
writeptr = readptr = 0;
consumer = producer = 0;//the num of waiting
}
int findEmpty(vector<int>& v, int len)
{
for(int i = 0; i < len; ++i)
{
if(v[i] == 0)
return i;
}
return -1;
}
int findDirty(vector<int>& v, int len)
{
for(int i = 0; i < len; ++i)
{
if(v[i] > 0)
return i;
}
return -1;
}
void show()
{
for(int i = 0; i < bufferSize; ++i)
{
if(buffer[i] > 0)
cout << " " << buffer[i] << " |";
else
cout << " |";
}
cout << "\nwriteptr = \t" << writeptr << "\treadptr = \t" << readptr << "\t";
if(producer)
cout << "PRODUCER wait : " << producer << "\t";
else
cout << "PRODUCER ready\t\t";
if(consumer)
cout << "CONSUMER wait : " << consumer;
else
cout << "CONSUMER ready";
cout << "\n";
}
void produce()
{
if(findEmpty(buffer, bufferSize) == -1) // buffer full
{
++id;
producer++;
waitQueue.push(id);
}
else
{
if(waitQueue.empty())
{
id++;
buffer[writeptr] = id;
}
else
{
producer--;
buffer[writeptr] = waitQueue.front();
waitQueue.pop();
}
writeptr = (writeptr + 1) % bufferSize;
}
}
void consume()
{
if(findDirty(buffer, bufferSize) == -1) // buffer empty
{
if(waitQueue.empty())
{
consumer++;
}
else
{
buffer[writeptr] = waitQueue.front();
waitQueue.pop();
writeptr = (writeptr + 1) % bufferSize;
}
}
else
{
buffer[readptr] = 0;
readptr = (readptr + 1) % bufferSize;
}
}
void work()
{
char c;
cin >> c;
while(c != 'q' && (c == 'p' || c == 'c'))
// q = quit p = produce one c = consume one
{
if(c == 'p')
{
produce();
}
else if(c == 'c')
{
consume();
}
show();
cin >> c;
}
}
int main(int argc, char const *argv[])
{
init();
work();
return 0;
}
转载于:https://www.cnblogs.com/lj95/p/10260723.html