Blue Flower

Chercher

Utilisation des sémaphores 

Rappel sur les Sémaphores

...

Sémaphore

public class Semaphore { 
  private int cpt = 0; 
  Semaphore (int c) { cpt = c;
} 
public void P() throws InterruptedException { 
 synchronized (this) { 
while (cpt == 0) { 
 this.wait ();
} 
 cpt--; 
}
} 
public void V() { 
synchronized (this) { 
cpt++; this.notify (); 
} 
} 
}

et c'est là l'essentiel du programme. La boucle while sert à la saisie du flux d'entrée .

 ........

 

Le dîner des philosohpes

// CS237 Concurrent Programming
// ===== ========== ===========
// First attempt at a solution to the dining philsopers problem.  
// The approach used is to represent each fork by a (binary) semaphore.
// This version picks up both  forks at once by putting the two actions
// in a synchronized block.

class philosopher extends Thread {

  static final Object lock = new Object() ;

  semaphore left, right ;
  int i ;

  public philosopher(int i, semaphore left,
                            semaphore right) {
    this.i = i ;
    this.left = left ;
    this.right = right ;
  }

// The next method is a random number generator.

  private int random(int n) {
    return (int) Math.round( n * Math.random() - 0.5 ) ;
  }

// The next method is used to 'kill time' while a philosopher thinks or eats.

  private void busy(int i, String s) { 
    System.out.println(i + " is " + s) ;
    try{ sleep(random(0)) ; } catch (InterruptedException e) { }
  }

  public void run() {
    do { busy(i, "thinking") ;
         synchronized (lock) { left.P() ;
                               System.out.println(i + " gets left fork") ;
                               right.P() ;
                               System.out.println(i + " gets right fork") ;
                               busy(i, "eating") ; }
         left.V() ; 
         System.out.println(i + " releases left fork") ;
         right.V() ;
         System.out.println(i + " releases right fork") ;
       } while (true) ;
  }

}

class dpp3 {

  static int N = 5 ;

  static semaphore fork[] = new semaphore[N] ;

  static philosopher p[] = new philosopher[N] ;

  public static void main(String [] args) {
    for(int i=0; i<N; i++) fork[i] = new semaphore(1) ;
    for(int i=0; i<N; i++) {
      p[i] = new philosopher(i, fork[i], fork[(i+1) % N]) ;
      p[i].start() ;
    }
  }

}

précédent