//DiningPhilosophers.cs----------code:seafrog----------------------------------------------------- using System; using System.Threading; using System.Windows.Forms;
using seafrog.Threading; using seafrog.Philosopher;
namespace DiningPhilosophers { public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Button button1; private System.ComponentModel.Container components = null; private System.Windows.Forms.ListBox listBox1; private Philosopher[] p=new Philosopher[5]; public Form1() { InitializeComponent();
public void ShowMessage(object sender,MessageArrivedEventArgs e) { switch(e.type) { case Philosopher.READY: listBox1.Items.Add("Philosopher("+e.philosopherData.PhilosopherId+") ready."); break; case Philosopher.EATING: listBox1.Items.Add("Philosopher("+ e.philosopherData.PhilosopherId+") eating "+ e.philosopherData.AmountToEat+" of "+ e.philosopherData.TotalFood+" food."); break; case Philosopher.THINKING: listBox1.Items.Add("Philosopher("+e.philosopherData.PhilosopherId+") thinking."); break; case Philosopher.FINISHED: listBox1.Items.Add("Philosopher("+e.philosopherData.PhilosopherId+") finished."); break; } } } }
//BaseThread.cs----------code:seafrog-------------------------------------------------------- using System; using System.Threading; namespace seafrog.Threading { //工作線程抽象類,作為對線程操作的封裝。 public abstract class WorkerThread { private object ThreadData; private Thread thisThread;
public object Data { get{return ThreadData;} set{ThreadData=value;} } public object IsAlive { get{return thisThread==null?false:thisThread.IsAlive;} } public WorkerThread(object data) { this.ThreadData=data; } public WorkerThread() { ThreadData=null; } public void Start() { thisThread=new Thread(new ThreadStart(this.Run)); thisThread.Start(); } public void Stop() { thisThread.Abort(); while(thisThread.IsAlive); thisThread=null; } protected abstract void Run(); } }
//Philosophers.cs----------code:seafrog-------------------------------------------------------- using System; using System.Threading; using seafrog.Threading; namespace seafrog.Philosopher { //封裝哲學家數據的結構 public struct PhilosopherData { public int PhilosopherId; public Mutex RightChopStick; public Mutex LeftChopStick; public int AmountToEat; public int TotalFood; }
public class Philosopher : seafrog.Threading.WorkerThread { public const int READY=0; public const int EATING=1; public const int THINKING=2; public const int FINISHED=3;
public Philosopher(object data):base(data){} public delegate void MessageArrivedHandler(Object sender,MessageArrivedEventArgs args); public event MessageArrivedHandler MessageArrival; public static int finished=0;
//事件:用來通知主窗體現在哲學家的狀態。 public class MessageArrivedEventArgs : EventArgs { public int type; public PhilosopherData philosopherData; public MessageArrivedEventArgs(int t,PhilosopherData pd) { type=t; philosopherData=pd; } } }