2014-10-18 167 views
-1

这个小脚本应该生成一个用户指定数量的随机数并打印它们。这是一个多线程脚本,我认为这是我的麻烦所在。我没有收到任何错误,但运行脚本时就挂起了。Ruby脚本永远挂起

num = [] 

while 0.upto ARGV[0].to_i do 
    num << rand{254} 
end 

current_index = 0 

while current_index < num.size 

chunk = num[current_index, 5] 
threads = [] 

chunk.each do |n| 
    threads << Thread.new do 
    puts n 
    end 
end 

threads.each do |thread| 
    thread.join 
end 

current_index += chunk.size 
end 
+1

你的问题是什么? – sawa 2014-10-19 00:10:54

+0

您应该避免使用与Ruby内置方法的名称相同的变量名称。也许你不熟悉方法[Enumerable#chunk](http://www.ruby-doc.org/core-2.1.1/Enumerable.html#method-i-chunk)。 – 2014-10-19 01:37:30

回答

1

不能使用while循环与upto

将其更改为:

0.upto ARGV[0].to_i do 
    num << rand(254) 
end 

它工作正常(我已经改变了牙套卷发一个,因为我相信你想254是参数在这里)。


旁注:

用Ruby编写线程程序时,该CRuby有GIL记住 - 全局解释器锁。因此,一次只能有一个线程运行。如果你想要不同的行为 - 例如切换到jRuby。有关GIL的更多信息,请参见f.e.这里:http://www.jstorimer.com/blogs/workingwithcode/8085491-nobody-understands-the-gil

+0

没有理由认为'while'不能与'upto'一起使用,但可能没有理由这样做。这里'0.upto ARGV [0] .to_i做; num << rand {254}; end'返回'0',所以我们留下'while 0 ... end',它与'while true ... end'相同。人们可以从这个循环中突破,但这不是在这里完成的。是的,''while''应该被删除,但是不要忘记删除最后的'end'。 – 2014-10-19 01:33:35

1

upto返回self,这是一个数字。所有不是falsenil在Ruby中都是真实的,包括数字。所以,你有一个while循环,其条件永远是真的,ergo永远不会停止。