2012-08-22 22 views
1

我正在玩線程,我發現我不能運行10000線程。Ruby 1.9.3-p140 - Ruby程序中的最大線程數?

它給了我下面的錯誤:

 threading.rb:23:in `initialize': can't create Thread (35) (ThreadError) 
     from threading.rb:23:in `new' 
     from threading.rb:23:in `block in <main>' 
     from threading.rb:22:in `times' 
     from threading.rb:22:in `<main>' 

然後我想看看什麼是最大數量,當我補到2046點一線,將Ruby運行代碼。

爲什麼2046?它似乎遵循的像512,1024,2046存儲器中的圖案...

的threading.rb代碼:

threads = [] 
    counter = 1000 

    ARGV.each do |a| 
     counter = a.to_i 
    end 

    lines = 0 

    counter.times do |i| 
     puts "This is index number #{i}." 
    end 

    puts "You've just seen the normal printing and serial programming.\n\n" 

    counter.times do |i| 
     Thread.new do 
     some_number = Random.rand(counter) 
     sleep 1 
     puts "I'm thread number #{i}. My random number is #{some_number}.\n" 
     lines += 1 
     end 
    end 

    messaged = false 
    while lines < counter 
     puts "\nWaiting to finish.\n" unless messaged 
     print '.' 
     puts "\n" if lines == counter 
     messaged = true 
    end 

    puts "\nI've printed #{lines} lines.\n" 
    puts "This is end of the program." 
+0

你在運行什麼操作系統?例如,在Linux上嘗試'cat/proc/sys/kernel/threads-max'。 – thoferon

+0

Ruby不支持線程瘋狂。嘗試另一種方法或另一種語言。 – Reactormonk

+0

我正在使用MacOS Lion Mountain。我不知道該怎麼看。 –

回答

1

OS X限制的線程的數目的過程可以生成到2046這適用到Ruby也是如此。

來源&充分的解釋:"How many threads is too many?"

On OSX, there's a hard limit on the number of threads that one process can spawn. On recent versions, that limit is somewhere around 2000 threads.

...

If I run this same bit of code on a Linux machine, I'm able to spawn 10,000 threads without blinking. So, it's possible to spawn a lot of threads, but you probably don't want to.

這是一個測試程序,你可以看到運行的極限。

1.upto(10_000) do |i| 
    Thread.new { sleep } 
    puts i 
end