G'day、スレッドデッドロック
私はRuby 1.9.3を使って簡単なマルチスレッド実験をしようとしていました。
コード:
require 'thread'
ary = *0..10
res = 0
mutex = Mutex.new
#cv = ConditionVariable.new
ary.each do |x|
p "Iteration no. #{x}"
t = Thread.new do
p "Thread taking care of #{x}"
mutex.synchronize do
#cv.wait(mutex)
res += x
t.stop
end
end
end
Thread.list.each do |t| t.join; end
puts res
コール
[email protected]:~/coding$ ruby --version
ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-linux]
[email protected]:~/coding$ ruby mt.rb
"Iteration no. 0"
"Iteration no. 1"
"Iteration no. 2"
"Iteration no. 3"
"Iteration no. 4"
"Thread taking care of 2"
"Thread taking care of 1"
"Thread taking care of 0"
"Thread taking care of 3"
"Iteration no. 5"
"Thread taking care of 4"
"Iteration no. 6"
"Thread taking care of 5"
"Iteration no. 7"
"Thread taking care of 6"
"Iteration no. 8"
"Thread taking care of 7"
"Iteration no. 9"
"Thread taking care of 8"
"Iteration no. 10"
"Thread taking care of 9"
"Thread taking care of 10"
mt.rb:21:in `join': deadlock detected (fatal)
from mt.rb:21:in `block in <main>'
from mt.rb:21:in `each'
from mt.rb:21:in `<main>'
私はここに、間違って何をしているのですか?私は多くのものを試しました。Thread#stop
の代わりにを呼び出し、完了したときにはThread
メソッドを呼び出しません。
ありがとうございます!
改訂コードは:それはミューテックスを保持している間
require 'thread'
ary = *0..10
res = 0
mutex = Mutex.new
ary.each do |x|
p "Iteration no. #{x}"
t = Thread.new do
p "Thread taking care of #{x}"
mutex.synchronize do
res += x
end
t.stop
end
end
Thread.list.each &:join
puts res
は、あなたの答えをいただき、ありがとうございます。残念ながら、これは動作しません。私は質問の最後に改訂コードを入れました。もしあなたが一見することができたら、私はそれを愛するでしょう。 –