这个小脚本应该生成用户指定数量的随机数并打印出来。这是一个多线程脚本,我认为这就是我的麻烦所在。我没有收到任何错误,但是运行脚本时会挂起。
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
您不能将while
循环与一起使用upto
。
更改为:
0.upto ARGV[0].to_i do
num << rand(254)
end
并且它正常工作(我将花括号更改为大括号,因为我相信您希望在此处将254作为参数)。
边注:
请记住,在用Ruby编写线程程序时,CRuby具有GIL-全局解释器锁。因此,一次只能运行一个线程。如果您想要不同的行为-例如切换到jRuby。有关GIL的更多信息,请访问以下网址:http : //www.jstorimer.com/blogs/workingwithcode/8085491-nobody-understands-the-gil
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句