Philosopher Example
using System;
using System.Threading;
class PhilosopherExample {
public static bool chopStick1Available = true;
public static bool chopStick2Available = true;
public static void Main() {
Thread philosopher1 = new Thread(new ThreadStart(GetChopSticks1));
Thread philosopher2 = new Thread(new ThreadStart(GetChopSticks2));
philosopher1.Start();
philosopher2.Start();
}
public static void GetChopSticks1() {
while (!chopStick1Available) {
Console.WriteLine("#1 waiting for 1st");
Thread.Sleep(100);
}
Console.WriteLine("#1 got 1st");
chopStick1Available = false;
while (!chopStick2Available) {
Console.WriteLine("#1 waiting for 2nd");
Thread.Sleep(100);
}
Console.WriteLine("#1 got 2nd");
chopStick2Available = false;
Console.WriteLine("#1 uses and releases chopsticks.");
chopStick1Available = true;
chopStick2Available = true;
}
public static void GetChopSticks2() {
while (!chopStick2Available) {
Console.WriteLine("#2 waiting for 1st");
Thread.Sleep(100);
}
Console.WriteLine("#2 got 1st chopstick.");
chopStick2Available = false;
while (!chopStick1Available) {
Console.WriteLine("#2 waiting for 2nd");
Thread.Sleep(100);
}
Console.WriteLine("#2 got 2nd chopstick.");
chopStick1Available = false;
Console.WriteLine("#2 uses and releases chopsticks.");
chopStick1Available = true;
chopStick2Available = true;
}
}
|
HTML code for linking to this page:
Related in same category :
-
-
-
|