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 }
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 }
您可以使用 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
显然,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,我觉得很完美。