首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ruby线程搞乱变量

Ruby线程搞乱变量
EN

Stack Overflow用户
提问于 2013-11-07 13:05:20
回答 1查看 196关注 0票数 0

我对红宝石很陌生,我想用线。出于目的,我希望线程能够生成线程,下面的代码如下:

代码语言:javascript
复制
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

输出是

代码语言:javascript
复制
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

前三行是正确的,但下面我搞砸了。

2 i=1,1 i=2和1 i= 3,输出的I=0。

我错过了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-07 13:09:16

使用for i in 1..3语句可能会使i在for块之外可用,并使其在父线程和子线程之间共享。

试着用块来代替:

代码语言:javascript
复制
(1..3).each do |i|
  # code
end

代码语言:javascript
复制
#!/usr/bin/env ruby

require 'thread'
semaphore = Mutex.new

thr = Array.new
outputs = Array.new
scripts = Array.new
(1..3).each do |i|
  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
(1..3).each do |i|
  thr[i].join
end
(1..3).each do |i|
  scripts[i].join
end
(1..3).each do |i|
  puts outputs[i]
end

代码语言:javascript
复制
denis@DB:~/wk $ ./test.rb 
adding 1 thread
ready to create 1 thread
adding 3 thread
ready to create 3 thread
adding 2 thread
ready to create 2 thread
in 1 thread
X1
in 3 thread
in 2 thread
X3
X2
a1
a2
a3
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19836739

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档