Philosopher Example : Producer Consumer « Thread « C# / CSharp Tutorial






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;
    }
}








20.22.Producer Consumer
20.22.1.Producer and consumer
20.22.2.Producer/consumer
20.22.3.Consumer Producer with Monitor
20.22.4.Philosopher Example