The C # Realization of the Philosophers ' dining problem

Source: Internet
Author: User
Tags abstract mutex sleep thread
Author of the question: Zhou Xiang

This is a program that I wrote in the semester of the operating system class and was organized into an article. I was posted on CSTC's Forum by my best friend Zeng: http://cstc.net.cn/bbs/viewtopic.php?t=457, here, I put it here, I hope to benefit everyone.



The process synchronization of operating system involves three classical problems: producer-consumer problem, reader-writer problem and philosophers ' dining problem. Here are some questions about the dining philosophers:
In the question of dining philosophers, a group of philosophers sat around a round table, each philosopher has only one chopstick on the left (of course he has a chopstick on his right side, but this is the chopstick on the left of his right philosopher), they think after eating, think for a while will be hungry, hungry to eat, however, in order to eat, They must get the chopsticks on the left and right. When each philosopher takes only one chopstick, he sits and waits for the other, and when every philosopher takes only one chopstick, a deadlock occurs. The traditional way to solve the deadlock problem is to refer to the concept of enhancement, but in C # In the case of System.Threading, the mutex in the middle of the word can be used by each philosopher to fame two semaphores Rightchopstick and Leftchopstick, assign values to it in the main program with 5 mutexes, and use WaitHandle to achieve exclusive access to chopsticks. This example is implemented using the Windows graphical interface, using events to inform the state of the interface philosopher.
Here's the code (run under 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
{
Worker thread abstract class, as an encapsulation of threading operations.
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 (The 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
{
Encapsulates the structure of the Philosopher's data
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&GT;0)
{
If the philosophers on both sides hold the chopsticks, wait.
WaitHandle.WaitAll (chopsticks);
Otherwise, eat.
Messagearrival (this,new Messagearrivedeventargs (EATING,PD));
Eat a portion of the meal.
Pd. TOTALFOOD-=PD. Amounttoeat;
Thread.Sleep (R.next (1000,5000));

Messagearrival (this,new Messagearrivedeventargs (THINKING,PD));
Put down the chopsticks on the left and right.
Pd. Rightchopstick.releasemutex ();
Pd. Leftchopstick.releasemutex ();

Thread.Sleep (R.next (1000,5000));
}
The food is all finished.
Messagearrival (this,new Messagearrivedeventargs (FINISHED,PD));
if (++finished==4)
System.Windows.Forms.MessageBox.Show ("All finished!");
}
}

Events: Used to inform the main form of the present philosopher's state.
public class Messagearrivedeventargs:eventargs
{
public int type;
Public Philosopherdata Philosopherdata;
Public Messagearrivedeventargs (int t,philosopherdata PD)
{
type=t;
PHILOSOPHERDATA=PD;
}
}
}




Finish


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.