Home   Cover Cover Cover Cover
 

Dining philosophers

Chap4_Ex12.cs
using System;
using System.Threading;


public class Philosopher {
  public static int MAX_THINK = 1000;
  public static int MAX_EAT = 1000;
  private Thread t;
  private bool running = true;
  private int nr;
  private bool[] forks;

  public Philosopher(int n, bool[] f) {
    nr = n;
    this.forks = f;
  }

  public void Start() {
    t = new Thread(new ThreadStart(Work));
    t.Start();
  }

  public void Work() {
    System.Random r = new Random(DateTime.Now.Millisecond);
    while(running) {
      Thread.Sleep(r.Next(MAX_THINK)); // thinking
      // now eating
      Monitor.Enter(forks);
      while(!forks[nr] && !forks[(nr+1)%5]) Monitor.Wait(forks);
      // reserve the left and the right fork for this philisopher
      forks[nr] = false;
      forks[(nr+1)%5] = false;
      Monitor.PulseAll(forks);
      Monitor.Exit(forks);
      // now eat
      Console.WriteLine("Philosopher {0} eats", nr);
      Thread.Sleep(r.Next(MAX_EAT)); // eating
      // after eating free the two forks
      Monitor.Enter(forks);
      forks[nr] = true;
      forks[(nr+1)%5] = true;
      Monitor.PulseAll(forks);
      Monitor.Exit(forks);
    }
  }

  public bool Running {
    get { return running; }
    set { running = value; }
  }  
}

public class Cap4_Ex12_Test {
  static bool[] forks;
  static Philosopher[] phil;

  public static void Main(string[] args) {
    // init 5 forks and set them to available = true
    forks = new bool[5];
    for(int i=0;i<5;i++) forks[i] = true;
    // create and start 5 philisophers
    phil = new Philosopher[5];
    for(int i=0;i<5;i++) {
      phil[i] = new Philosopher(i, forks);
      phil[i].Start();
    }
    
  }
}