哲学家就餐问题是多线程同步中的经典问题,本文在 windows 上用 C/C++ 实现该问题。
之前在网上看到一个该问题的实现:http://dev.csdn.net/article/77/77383.shtm,是用临界区作的,但是感觉不是太好,因为当一个哲学家在试图取叉子用餐的时候,其他哲学家必须等待,而实际上,当 1 号哲学家
取叉子时,3号哲学家也可以取叉子,他们是不冲突的。
假设有 5 个哲学家,有 5 把叉子,每个哲学家有思考,饥饿,和吃饭三个状态。我们用 5 个信号量分别表示 5 把叉子。在打印哲学家状态时,使用一个互斥体 mutex ,否则打印出来是乱的。
源代码如下:
// PhilosopherDining.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "windows.h"
#include <process.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
const unsigned int PHILOSOPHER_NUM