-
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Threading;
-
- namespace Philosopher
- {
- enum PhilosopherState { Thinking, Hungry, Ready, Unavailable, Eating, Done, };
- class Fork
- {
- bool _Owned = false;
- public Fork() { }
- public bool Owned
- {
- get { return _Owned; }
- set { _Owned = value; }
- }
- }
-
- class Waiter
- {
- Thread ServeThread;
- Philosopher[] Philosphers;
- bool ThreadRunning;
-
- public Waiter(Philosopher[] phs)
- {
- Philosphers = phs;
- ServeThread = new Thread(StartService);
- ServeThread.Start();
- }
- public void Stop() { ThreadRunning = false; }
-
- void StartService()
- {
- ThreadRunning = true;
- int i = 0;
- while (ThreadRunning) { //轮询
- if (Philosphers[i].State == PhilosopherState.Hungry) { //哲学家饿了
- if (!Philosphers[i].Left.Owned && !Philosphers[i].Right.Owned) {
- Philosphers[i].Left.Owned = true;
- Philosphers[i].Right.Owned = true;
- Philosphers[i].State = PhilosopherState.Ready; //通知哲学家可以就餐
- }
- else {
- Philosphers[i].State = PhilosopherState.Unavailable; //没有足够资源
- }
- Philosphers[i].WaitEvent.Set(); //哲学家结束等待
- }
- else if (Philosphers[i].State == PhilosopherState.Done) { //哲学家吃饱了
- Philosphers[i].Left.Owned = false; //回收
- Philosphers[i].Right.Owned = false;
- Philosphers[i].WaitEvent.Set();
- }
- i = (i + 1) % Philosphers.Length; //下一个哲学家
- Thread.Sleep(20);
- }
- }
- }
-