Ruby线程和变量 [英] Ruby threads and variable
问题描述
为什么结果不是从1到10,而是只有10s?
Why the result is not from 1 to 10, but 10s only?
require 'thread'
def run(i)
puts i
end
while true
for i in 0..10
Thread.new{ run(i)}
end
sleep(100)
end
结果:
10
10
10
10
10
10
10
10
10
10
10
为什么循环?我正在运行while循环,因为稍后我想一直遍历数据库表并回显从数据库中检索到的所有记录.
Why loop? I am running while loop, because later I want to iterate through the DB table all the time and echo any records that are retrieved from the DB.
推荐答案
传递给Thread.new
的块实际上可能在将来的某个时刻开始,并且到那时i
的值可能已更改.就您而言,在所有线程实际运行之前,它们都已增加到10
.
The block that is passed to Thread.new
may actually begin at some point in the future, and by that time the value of i
may have changed. In your case, they all have incremented up to 10
prior to when all the threads actually run.
要解决此问题,请使用除了块之外,Thread.new
还接受参数:
To fix this, use the form of Thread.new
that accepts a parameter, in addition to the block:
require 'thread'
def run(i)
puts i
end
while true
for i in 0..10
Thread.new(i) { |j| run(j) }
end
sleep(100)
end
这将在调用new
时将块变量j
设置为i
的值.
This sets the block variable j
to the value of i
at the time new
was called.
这篇关于Ruby线程和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!