// The behaviour of the first philosopher. public static void Phil1(Object x) { Philosophers phil = (Philosophers)x; Object thisLock = new Object(); while (true) { // Wait until the right-hand side fork is available. while (phil.Forks[4]) { ; } // Take the fork. lock (thisLock) { phil.Forks[4] = true; } // Wait until the left-hand side fork is available. while (phil.Forks[0]) { ; } lock (thisLock) { phil.Forks[0] = true; } // Showing the eateng process with assigning a green color to the indicator. lock (gr1) gr1.FillEllipse(Brushes.Green, phil.phil1.X, phil.phil1.Y, 50, 50); // Duration of eating process. Thread.Sleep(2000); // Leaving forks. lock (thisLock) { phil.Forks[4] = false; phil.Forks[0] = false; } // Showing the thinking process with assigning a yellow color to the indicator. lock (gr1) gr1.FillEllipse(Brushes.Yellow, phil.phil1.X, phil.phil1.Y, 50, 50); // Duration of thinking process. Thread.Sleep(2000); // The philosopher is ready to wait for his turn again. Setting a red color to the indicator. lock (gr1) gr1.FillEllipse(Brushes.Red, phil.phil1.X, phil.phil1.Y, 50, 50); } }
public static void Phil5(Object x) { Philosophers phil = (Philosophers)x; Object thisLock = new Object(); while (true) { while (phil.Forks[3]) { ; } lock (thisLock) { phil.Forks[3] = true; } while (phil.Forks[4]) { ; } lock (thisLock) { phil.Forks[4] = true; } lock (gr1) gr1.FillEllipse(Brushes.Green, phil.phil5.X, phil.phil5.Y, 50, 50); Thread.Sleep(2000); lock (thisLock) { phil.Forks[3] = false; } lock (thisLock) { phil.Forks[4] = false; } lock (gr1) gr1.FillEllipse(Brushes.Yellow, phil.phil5.X, phil.phil5.Y, 50, 50); Thread.Sleep(2000); lock (gr1) gr1.FillEllipse(Brushes.Red, phil.phil5.X, phil.phil5.Y, 50, 50); } }
// Start dining. private void button1_Click(object sender, EventArgs e) { gr1 = pictureBox1.CreateGraphics(); CreateTable(); Philosophers phils = new Philosophers(); ph1 = new Thread(Phil1); ph2 = new Thread(Phil2); ph3 = new Thread(Phil3); ph4 = new Thread(Phil4); ph5 = new Thread(Phil5); ph1.Start(phils); ph2.Start(phils); ph3.Start(phils); ph4.Start(phils); ph5.Start(phils); }