哲學家就餐問題的C#實現
2024-07-21 02:19:30
供稿:網友
國內最大的酷站演示中心!
撰文:周翔
這是我在上操作系統課的那個學期寫的一段程序,并組織成了一篇文章。當初被我的摯友曾毅發表在cstc的論壇上:http://cstc.net.cn/bbs/viewtopic.php?t=457,在此,我把它貼在這兒,希望對大家有所裨益。
學操作系統的進程同步都要涉及到三個經典問題:生產者-消費者問題、讀者-寫者問題和哲學家就餐問題。下面來介紹一下哲學家就餐問題:
哲學家就餐問題中,一組哲學家圍坐在一個圓桌旁,每個哲學家的左邊都只有一只筷子(當然他的右邊也有一只筷子,但是這是他右邊哲學家的左邊的筷子),他們吃完了就思考,思考了一會就會餓,餓了就想吃,然而,為了吃飯,他們必須獲得左邊和右邊的筷子。當每個哲學家只拿有一只筷子的時候,會坐者等另一只筷子,在每個哲學家都只拿一個筷子的時候,就會發生死鎖。傳統的解決死鎖問題的方法是引用管程的概念,但是在c#中來實現的話可以使system.threading中的mutex為每個哲學家來聲名兩個信號量rightchopstick和leftchopstick,在主程序中用5個mutex賦值給它,用waithandle來實現對筷子的獨占訪問。這個例子是用windows圖形界面實現,用事件來通知界面哲學家的狀態。
以下是代碼(在vs.net 下運行通過):
//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();
mutex[] chopsticks=new mutex[5];
for(int i=0;i<5;i++)
{
chopsticks[i]=new mutex(false);
}
for(int i=0;i<5;i++)
{
philosopherdata pd;
pd.philosopherid=i;
pd.rightchopstick=chopsticks[(i+1)%5];
pd.leftchopstick=chopsticks[(i+4)%5];
pd.amounttoeat=5;
pd.totalfood=35;
p[i]=new philosopher(pd);
p[i].messagearrival+=new philosopher.messagearrivedhandler(showmessage);
}
}
protected override void dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.dispose();
}
}
base.dispose( disposing );
}
#region windows form designer generated code
private void initializecomponent()
{
this.button1 = new system.windows.forms.button();
this.listbox1 = new system.windows.forms.listbox();
this.suspendlayout();
//
// button1
//
this.button1.location = new system.drawing.point(8, 224);
this.button1.name = "button1";
this.button1.size = new system.drawing.size(272, 40);
this.button1.tabindex = 1;
this.button1.text = "go to restaurant";
this.button1.click += new system.eventhandler(this.button1_click);
//
// listbox1
//
this.listbox1.itemheight = 12;
this.listbox1.name = "listbox1";
this.listbox1.size = new system.drawing.size(296, 220);
this.listbox1.tabindex = 2;
//
// form1
//
this.autoscalebasesize = new system.drawing.size(6, 14);
this.clientsize = new system.drawing.size(292, 273);
this.controls.addrange(new system.windows.forms.control[] {
this.listbox1,
this.button1});
this.name = "form1";
this.text = "form1";
this.resumelayout(false);
}
#endregion
[stathread]
static void main()
{
application.run(new form1());
}
private void button1_click(object sender, system.eventargs e)
{
for(int i=0;i<5;i++)
p[i].start();
}
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;
protected override void run()
{
philosopherdata pd=(philosopherdata)data;
random r=new random(pd.philosopherid);
messagearrival(this,new messagearrivedeventargs(ready,pd));
waithandle[] chopsticks=new waithandle[]{pd.leftchopstick,pd.rightchopstick};
while(pd.totalfood>0)
{
//如果兩邊的哲學家拿著筷子,則等待。
waithandle.waitall(chopsticks);
//否則,吃飯。
messagearrival(this,new messagearrivedeventargs(eating,pd));
//把飯吃掉一部分。
pd.totalfood-=pd.amounttoeat;
thread.sleep(r.next(1000,5000));
messagearrival(this,new messagearrivedeventargs(thinking,pd));
//放下左邊和右邊的筷子。
pd.rightchopstick.releasemutex();
pd.leftchopstick.releasemutex();
thread.sleep(r.next(1000,5000));
}
//飯都吃完了。
messagearrival(this,new messagearrivedeventargs(finished,pd));
if(++finished==4)
system.windows.forms.messagebox.show("all finished!");
}
}
//事件:用來通知主窗體現在哲學家的狀態。
public class messagearrivedeventargs : eventargs
{
public int type;
public philosopherdata philosopherdata;
public messagearrivedeventargs(int t,philosopherdata pd)
{
type=t;
philosopherdata=pd;
}
}
}
( 完)