
// DiningPhilTickets.java
// Andrew Davison, ad@coe.psu.ac.th, May 2023

/* The Dining philosophers problem:
      https://en.wikipedia.org/wiki/Dining_philosophers_problem

  Dining philosophers using tickets to avoid deadlock.
  The tickets have the tuple form:
     ("TICKET")
  which means that aa philipospher thread can select any
  one in order to continue.

  Usage:
    > compile.bat DiningPhilTickets.java
    > run.bat DiningPhilTickets

    Part of the application made up of:
       * DiningPhilTickets.java
       * PhilTicket.java


  Other versions: 
    * DiningPhilosophers.java
    * RemoteDiningPhilosophers.java
*/



import org.jspace.*;


public class DiningPhilTickets
{
  private static final int NUM_PHILS = 10;


  public static void main(String[] args)
                     throws InterruptedException
  {
    // Space space = new SequentialSpace();
    Space space = new VisSpace(500);   // faster than the default

    System.out.println("Put " + NUM_PHILS +
                              " forks on the table...");
    for (int i = 0; i < NUM_PHILS; i++)
      space.put("FORK", i);

    /* deadlock is avoided by allocating one less tickets than
       there are philosophers */
    System.out.println("Put " + (NUM_PHILS-1) +
                                  " tickets on the table...");
    for (int i = 0; i < NUM_PHILS-1; i++)
      space.put("TICKET");

    PrintAreas pas = new PrintAreas(NUM_PHILS);

    System.out.println("Create " + NUM_PHILS + " philosophers");
    for (int i = 0; i < NUM_PHILS; i++)
      new Thread(
         new PhilTicket(i, pas, space, i, (i+1)%NUM_PHILS),
         "PHIL-"+i).start();
  }  // end of main()

}  // end of DiningPhilTickets class
