1# 2# The Dining Philosophers - thread example 3# 4require "thread" 5 6srand 7#srand 8N=9 # number of philosophers 9$forks = [] 10for i in 0..N-1 11 $forks[i] = Mutex.new 12end 13$state = "-o"*N 14 15def wait 16 sleep rand(20)/10.0 17end 18 19def think(n) 20 wait 21end 22 23def eat(n) 24 wait 25end 26 27def 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 47end 48 49for n in 0..N-1 50 Thread.start(n){|i| philosopher(i)} 51 sleep 0.1 52end 53 54sleep 55