2

Heroku 显然限制了线程数,并ThreadError (can't create Thread (11))在达到限制时发出错误。

将线程数限制在定义的限制范围内的最简单方法是什么N?假设循环如下所示:

beers.each do |aBeer|
   threads << Thread.new(aBeer) { |beer|
      drink(beer)
   }
end
threads.each { |aThread|  aThread.join }
4

2 回答 2

4

您可以使用 gem ruby​​-thread,它是线程池。安装gem install thread

require 'thread/pool'
N = 4
pool = Thread.pool(N) # COUNT OF YOUR THREADS 

beers.each do |aBeer|
   pool.process {
     drink(aBeer)
   }
end

pool.shutdown
于 2013-08-16T03:01:19.180 回答
2

显然,Heroku 限制了固定数量的线程(256),以及内存限制(512 或 1024 MB,取决于您的选择)。

https://devcenter.heroku.com/articles/limits#dyno-memory


我会这样做,因为啤酒在每个线程之间公平地重新分配。

thread_limit = 10 # Here you define your thread limit
beers_per_thread = beers.count / thread_limit # Number of beers / thread 
thread_pool = nil
beers.each_with_index.map {|beer, index| 
    if index % beers_per_thread == 0
        puts "New Thread Created at beer #{index}, hips.."
        thread_pool << thread
        thread = Thread.new
    end
    # Thread stuff
}

thread_pool.each do |thread|
    # process thread
end

再加上Bigxiang thread_pool,我觉得很完美。

于 2013-08-16T03:08:55.197 回答