
// DiningPhilosophers.java
// Michele Loreti and the jSpace Developers, 2017
// Modified by Andrew Davison, ad@coe.psu.ac.th, May 2023

/* The Dining philosophers problem:
      https://en.wikipedia.org/wiki/Dining_philosophers_problem

   Deadlock is avoided by code in Philosopher.java.

  Original example at:
     https://github.com/pSpaces/jSpace/tree/master/examples/DiningPhilosophers/src/main/java/org/jspace/examples/df

  Usage:
    > compile.bat DiningPhilosophers.java
    > run.bat DiningPhilosophers

    Part of the application made up of:
       * DiningPhilosophers.java
       * Philosopher.java

  Other versions: 
    * RemoteDiningPhilosophers.java
    * DiningPhilTickets.java
        -- uses tickets to avoid deadlocks
*/



import org.jspace.*;


public class DiningPhilosophers
{
  private static final int NUM_PHILS = 5;


  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);

    PrintAreas pas = new PrintAreas(NUM_PHILS);

    System.out.println("Create " + NUM_PHILS + " philosophers");
    for(int i=0; i < NUM_PHILS; i++) {
      new Thread(
           new Philosopher(i, pas, space, i, (i+1)%NUM_PHILS),
           "PHIL-"+i).start();
    }
  } /* main */


}  // end of DiningPhilosophers class
