deadlock_test.rb

Christopher Bottaro, 01/12/2011 01:59 AM

Download (554 Bytes)

 
1
require "thread"
2
require "timeout"
3

    
4
def calc_fib(n)
5
  if n == 0
6
    0
7
  elsif n == 1
8
    1
9
  else
10
    calc_fib(n-1) + calc_fib(n-2)
11
  end
12
end
13

    
14
lock = Mutex.new
15

    
16
threads = 20.times.collect do
17
  Thread.new do
18
    20.times do
19
      begin
20
        Timeout.timeout(0.25) do
21
          lock.synchronize{ calc_fib(1000) }
22
        end
23
      rescue ThreadError => e
24
        puts "#{e.class}: #{e.message}:\n" + e.backtrace.join("\n") + "\n\n"
25
      rescue Timeout::Error => e
26
        #puts e.class
27
        nil
28
      end
29
    end
30
  end
31
end
32

    
33
threads.each{ |t| t.join }