操作系统实验二总结(生产者消费者问题)

为了这个实验二,资料查了巨多,pv操作什么的好不容易弄明白了,但是感觉老师要求的好像用不到这个。

大部分都是某位同学的成果哈哈哈。

自己总结了一下:

1.队列和链表在c++中是可以直接用已经有的模板的。

2.学会用指针进行遍历。

3.消费者要是能放到buffer里就看生产者等待队列里有没有人,有人就唤醒一个生产者。

4.要是buffer只有1那么大,最终完成链表中必定是生产者和消费者交替,这是一个验证程序对错的方法。

#include
#include
#include
#include
#include

using namespace std;
typedef struct 
{
	int type;//进程类型标号 0 生产者 1位消费者
	int ID;//进程系统号  1-10
	int state;//进程状态 0就绪 1等待 2完成
	char product;//进程产品 字符
	
}PCB;

int buffersize = 2;//缓冲区大小
queueready;
queueproducerwait;//生产者等待队列
queueconsumerwait;//消费者等待队列
listover;//收集已经运行结束的进程
int buffercount = 0;
int buffer[3];
void Producer(PCB &p)
{
	if (buffercount < 2)
	{
		buffercount++;
		buffer[buffercount] = p.ID;
		if (!consumerwait.empty())
		{
			PCB temp;
			temp = consumerwait.front();
			temp.state = 0;
			ready.push(temp);
			consumerwait.pop();
		}
		
		over.push_back(p);
		p.state = 2;
	}
	else
	{
		p.state = 1;
		producerwait.push(p);
	}

}

void Consumer(PCB &p)
{
	if (buffercount != 0)
	{
		buffer[buffercount] = NULL;
		buffercount--;
		over.push_back(p);
		if (!producerwait.empty())
		{
			PCB temp;
			temp = producerwait.front();
			temp.state = 0;
			ready.push(temp);
			producerwait.pop();
		}
		p.state = 2;
	}
	else
	{
		p.state = 1;
		consumerwait.push(p);
	}
}


int main()
{
	PCB p[10];
	for (int i = 0; i < 10; i++)//对模块进行初始化
	{
		p[i].type = rand() % 2;
		p[i].ID = i + 1;
		p[i].state = 0;
		p[i].product = 'a'+i;
		ready.push(p[i]);
	}
	while (!ready.empty())
	{
		PCB t;
		t = ready.front();
		ready.pop();
		if (t.type == 0)//如果是生产者
		{
			Producer(t);
		}
		else
		{
			Consumer(t);
		}
		cout << "****************就绪队列:****************" << endl;
		queue_ready;
		_ready = ready;
		while (!_ready.empty())
		{
			PCB te = _ready.front();
			cout <<"进程类型标号: "<< te.type<<" 进程系统号:  "<::iterator iter;
		std::list::iterator start = over.begin();
		for(iter=over.begin();iter!=over.end();iter++)
		{
			PCB p = *iter;
			cout << "进程类型标号: " << p.type << " 进程系统号:  " << p.ID << " 进程状态: " << p.state << " 进程产品: " << p.product << " " << endl;
		}

		cout << "****************生产者等待队列:****************" << endl;
		queue_producerwait;
		_producerwait = producerwait;
		while (!_producerwait.empty())
		{
			PCB te = _producerwait.front();
			cout << "进程类型标号: " << te.type << " 进程系统号:  " << te.ID << " 进程状态: " << te.state << " 进程产品: " << te.product << " " << endl;
			_producerwait.pop();
		}
		cout << "****************消费者等待队列:****************" << endl;
		queue_consumerwait;
		_consumerwait = consumerwait;
		while (!_consumerwait.empty())
		{
			PCB te = _consumerwait.front();
			cout << "进程类型标号: " << te.type << " 进程系统号:  " << te.ID << " 进程状态: " << te.state << " 进程产品: " << te.product << " " << endl;
			_consumerwait.pop();
		}
		cout << endl;
		cout << endl;
	}
	system("pause");
	return 0;
}

最终结果图

操作系统实验二总结(生产者消费者问题)_第1张图片

自己画的自己理解的流程图

操作系统实验二总结(生产者消费者问题)_第2张图片

操作系统实验二总结(生产者消费者问题)_第3张图片

ps前一段时间学校oj竟更新了,原以为储存在学校网站和安全啊,我的数据结构代码啊,伤心,看来一定要多备份!

你可能感兴趣的:(解题报)