东北大学操作系统实验:进程同步和通信(生产者消费者问题模拟)

//producer_consumer.cc

#include
#include
#include
using namespace std;

const int bufferSize = 8;
vector buffer(bufferSize);
queue 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& v, int len)
{
	for(int i = 0; i < len; ++i)
	{
		if(v[i] == 0)
			return i;
	}
	return -1; 
}

int findDirty(vector& 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;
}

你可能感兴趣的:(操作系统)