2012年10月25日木曜日

rubyのthread


Queue をpopするとき、空だと、Threadは、sleep(stop)するらしい。join中に、すべてのThreadが、sleep(stop)だと、dead lockとなるらしい。

indou@MacBook:work:$ cat ts2.rb
require 'thread'

array_size = ARGV[0].to_i

q = Queue.new
10.times {|i| q.push "no:#{i}"}
q.push nil

arrays = Array.new(array_size) do |i|
  Thread.new do
    while cnt = q.pop
      puts "Thread #{i}: no:#{cnt}"
    end
  end
end
arrays.each do |t|
  t.join
end

puts "finish!!"
indou@MacBook:work:$ ruby ts2.rb 1
Thread 0: job0
Thread 0: job1
Thread 0: job2
Thread 0: job3
Thread 0: job4
Thread 0: job5
Thread 0: job6
Thread 0: job7
Thread 0: job8
Thread 0: job9
finish!!
indou@MacBook:work:$ ruby ts2.rb 2
Thread 0: job0
Thread 0: job2
Thread 0: job3
Thread 0: job4
Thread 0: job5
Thread 0: job6
Thread 0: job7
Thread 0: job8
Thread 0: job9
Thread 1: job1
ts2.rb:17:in `join': deadlock detected (fatal)
     from ts2.rb:17:in `block in
'
     from ts2.rb:16:in `each'
     from ts2.rb:16:in `
'
indou@MacBook:work:$ diff ts2.rb ts2.2.rb
7c7,10
< q.push nil
---
> array_size.times do
>   puts "."
>   q.push nil
> end
indou@MacBook:work:$ ruby ts2.2.rb 1
.
Thread 0: job0
Thread 0: job1
Thread 0: job2
Thread 0: job3
Thread 0: job4
Thread 0: job5
Thread 0: job6
Thread 0: job7
Thread 0: job8
Thread 0: job9
finish!!
indou@MacBook:work:$ ruby ts2.2.rb 2
.
.
Thread 0: job0
Thread 0: job1
Thread 0: job2
Thread 0: job3
Thread 0: job4
Thread 0: job5
Thread 0: job6
Thread 0: job8
Thread 0: job9
Thread 1: job7
finish!!
indou@MacBook:work:$ 

0 件のコメント: