操作系统进程调度算法——哲学家进餐问题

问题描述:

一个圆桌子上围坐着五个哲学家,他们的左手边分别摆了一支筷子,他们不听进行思考和进餐,当要进餐前只有同时拿到左右两支筷子的时候才能开始进餐。哲学家的编号用i表示,他们左手边筷子编号为i,右手边筷子编号为(i+1)%5。本文中哲学家只有在左右两支筷子都不被使用的时候才能拿起筷子进餐.。

#include <iostream>
#include <stdlib.h>
using namespace std;

typedef struct semaphore {
	int mutex;//取筷子的互斥信号
	int chopstick[5];//5根筷子的互斥信号
}*semaphoreptr;

class Philosopher {
public:
	int num;//哲学家的编号
	int sign;//用来标记该进程是否成功申请了资源
	Philosopher(int a):num(a),sign(0){}
	~Philosopher(){}
	void wait(semaphoreptr s);
	void signal(semaphoreptr s);
};
void Philosopher::wait(semaphoreptr s) {
	if (s->mutex == 1) {
		if (s->chopstick[num] == 1 && s->chopstick[(num+1)%5] == 1) {
			//只有当哲学家的左右筷子都没有被取走的时候才能取筷子
			s->mutex = 0;
			s->chopstick[num] = s->chopstick[(num + 1) % 5] = 0;//表示取走左右的筷子
			this->sign = 1;//表示已经成功申请了资源
		}
		else {
			cout <<num<<"号哲学家无法取筷子,因为有其他哲学家拿走了左/右的筷子..." << endl;
			return;
		}
	}
	else {
		cout <<num<< "号哲学家无法取筷子,因为有其他哲学家正在取筷子..." << endl;
		return;
	}
}
void Philosopher::signal(semaphoreptr s) {
	if (this->sign == 1) {
		//表示该进程成功申请到资源
		cout << num << "号哲学家进餐..." << endl;
		s->mutex = 1;
		s->chopstick[num] = s->chopstick[(num + 1) % 5] = 1;//释放左右筷子
		this->sign = 0;
	}
	else {
		cout << num << "号哲学家没有拿到两支筷子,无法进餐..." << endl;
		return;
	}
}
int main()
{
	Philosopher p0(0), p1(1), p2(2), p3(3), p4(4);
	semaphoreptr s = (semaphore *)malloc(sizeof(semaphore));
	s->mutex = 1;
	for (int i = 0; i < 5; i++)
		s->chopstick[i] = 1;
	p0.wait(s);
	p1.wait(s);
	p0.signal(s);
	p1.wait(s);
	p2.wait(s);
	p2.signal(s);
	p1.signal(s);
    return 0;
}
调试结果:

参考书籍: 王道 《2018年操作系统考研复习指导》

猜你喜欢

转载自blog.csdn.net/haohulala/article/details/80615220