* io.c (rb_open_file): encoding in mode string was ignored if perm is
[ruby-svn.git] / sample / philos.rb
blob5c8f43c8198f6c2e9b3a8689dbb5497cf84f49e4
2 # The Dining Philosophers - thread example
4 require "thread"
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
15 def wait
16   sleep rand(20)/10.0
17 end
19 def think(n)
20   wait
21 end
23 def eat(n)
24   wait
25 end
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
49 for n in 0..N-1
50   Thread.start(n){|i| philosopher(i)}
51   sleep 0.1
52 end
54 sleep