Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将唯一变量传递到Ruby线程_Ruby_Multithreading_Variables - Fatal编程技术网

将唯一变量传递到Ruby线程

将唯一变量传递到Ruby线程,ruby,multithreading,variables,Ruby,Multithreading,Variables,我正在为for循环创建线程,我想使用for循环的I作为每个特定线程的名称。当我运行此操作时,我得到的不是1,2或2,1,而是2。有没有更好/更安全的方法将变量传递到线程中 ts = [] for i in 1..2 do ts.push( Thread.new(i) do x = i puts x end) end ts.each do |t| t.join() end 可以通过块传递变量 ts = [] for i in 1..2 do ts.push( T

我正在为
for
循环创建线程,我想使用
for
循环的
I
作为每个特定线程的名称。当我运行此操作时,我得到的不是
1
2
2
1
,而是
2
。有没有更好/更安全的方法将变量传递到线程中

ts = []
for i in 1..2 do
  ts.push( Thread.new(i) do
    x = i
    puts x
  end)
end
ts.each do |t|
  t.join()
end

可以通过块传递变量

ts = []

for i in 1..2 do
  ts.push( Thread.new(i) do |i|
    x = i
    puts x
  end)
end

ts.each do |t|
  t.join()
end

# => 1
# => 2

您的问题是,您引用的
i
不是传递给线程的块变量,而是在线程外部定义的
i
。您需要将
|i |
添加到它,您将得到
1
2
2
1

ts = []
for i in 1..2 do
  ts.push( Thread.new(i) do |i|
    x = i
    puts x
  end)
end
ts.each do |t|
  t.join()
end
顺便说一句,一种更为粗俗的写作方式是:

ts = (1..2).map do |i|
  Thread.new(i) do |i|
    puts i
  end
end.each(&:join)
如果要为每个线程寻找唯一的名称,我建议使用线程的对象id

ts = (1..2).map do
  Thread.new do
    puts Thread.current.object_id
  end
end.each(&:join)

不要忘记主
for
循环中的
i
是共享的。