我是 ruby 新手,想使用线程。有意地,我希望线程产生线程,我有以下代码:
require 'thread'
semaphore = Mutex.new
thr = Array.new
outputs = Array.new
scripts = Array.new
for i in 1..3
thr[i] = Thread.new do
puts "adding #{i} thread\n"
puts "ready to create #{i} thread\n"
scripts[i]= Thread.new do
puts "in #{i} thread\n"
puts "X#{i}\n"
outputs[i] = "a#{i}"
end
end
end
for i in 1..3
thr[i].join
end
for i in 1..3
scripts[i].join
end
for i in 1..3
puts outputs[i]
end
输出是
adding 1 thread
adding 2 thread
adding 3 thread
ready to create 3 thread
ready to create 1 thread
ready to create 1 thread
in 1 thread
in 1 thread
in 2 thread
X2
X3
X1
C:/Users/user/workspace/ruby-test/test.rb:61: undefined method `join' for nil:NilClass (NoMethodError)
from C:/Users/liux14/workspace/ruby-test/test.rb:60:in `each'
from C:/Users/liux14/workspace/ruby-test/test.rb:60
前三行是正确的,但后面的 i 就搞砸了。
两个 i = 1,一个 i = 2,一个 i = 3。而 output[i] 的一个为 nil。
我错过了什么?