sample/philos.rb


DEFINITIONS

This source file includes following functions.


   1  #
   2  # The Dining Philosophers - thread example
   3  #
   4  require "thread"
   5  
   6  srand
   7  #srand
   8  N=9                             # number of philosophers
   9  $forks = []
  10  for i in 0..N-1
  11    $forks[i] = Mutex.new
  12  end
  13  $state = "-o"*N
  14  
  15  def wait
  16    sleep rand(20)/10.0
  17  end
  18  
  19  def think(n)
  20    wait
  21  end
  22  
  23  def eat(n)
  24    wait
  25  end
  26  
  27  def philosopher(n)
  28    while TRUE
  29      think n
  30      $forks[n].lock
  31      if not $forks[(n+1)%N].try_lock
  32        $forks[n].unlock          # avoid deadlock
  33        next
  34      end
  35      $state[n*2] = ?|;
  36      $state[(n+1)%N*2] = ?|;
  37      $state[n*2+1] = ?*;
  38      print $state, "\n"
  39      eat(n)
  40      $state[n*2] = ?-;
  41      $state[(n+1)%N*2] = ?-;
  42      $state[n*2+1] = ?o;
  43      print $state, "\n"
  44      $forks[n].unlock
  45      $forks[(n+1)%N].unlock
  46    end
  47  end
  48  
  49  for n in 0..N-1
  50    Thread.start(n){|i| philosopher(i)}
  51    sleep 0.1
  52  end
  53  
  54  sleep