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#join
вместо 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
Спасибо за ваш ответ. К сожалению, это не сработает. Я вернул пересмотренный код в конце вопроса. Мне бы это понравилось, если бы вы могли взглянуть. –