【问题标题】:Ruby 1.9.3-p140 - Maximum number of threads in a Ruby program?Ruby 1.9.3-p140 - Ruby 程序中的最大线程数?
【发布时间】:2012-08-22 13:28:54
【问题描述】:

我正在玩 Thread,我发现我无法运行 10000 个线程。

它给了我以下错误:

        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."

【问题讨论】:

  • 你在什么操作系统上运行?例如,在 Linux 上尝试 cat /proc/sys/kernel/threads-max
  • Ruby 不支持线程疯狂。尝试另一种方法或另一种语言。
  • 我正在使用 MacOS Lion Mountain。我不知道怎么看。
  • Tass,我也认为 Ruby 不支持线程,但是当我这样做时,与没有线程的相同代码相比,区别是白天和黑夜。由于每次睡眠 1,没有 Thread 的相同代码至少需要 1000 秒才能运行。使用线程,使用时间 ruby​​ threading.rb 测量只需 1.8 ~ 2 秒。问题在于最大数量的线程。我在运行 1.9.3-p140 版本的 8G RAM 的 MPB i7 上运行。我也尝试过使用 Fiber,但这个过程需要 1000 多秒,就像没有 Thread 的代码一样。它表明 Fiber 只是一个任务管理系统。

标签: ruby multithreading thread-safety mutex fibers


【解决方案1】:

OS X 将一个进程可以生成的线程数限制为 2046。这也适用于 Ruby。

来源&完整解释:"How many threads is too many?"

在 OSX 上,一个进程可以生成的线程数有硬性限制。在最近的版本中,这个限制大约是 2000 个线程。

...

如果我在 Linux 机器上运行同样的代码,我可以在不眨眼的情况下生成 10,000 个线程。因此,可以生成很多线程,但您可能不想这样做。

这是一个您可以运行以查看限制的测试程序。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多