2014-10-18 120 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永遠不會停止。