我找不到适合Ruby的ThreadPool实现,所以我写了我的(部分基于此处的代码:http://web.archive.org/web/20081204101031/http : //snippets.dzone.com : 80/ posts/show/3276,但更改为等待/信号和ThreadPool关闭的其他实现.但是经过一段时间的运行(有100个线程并处理大约1300个任务),它在第25行死机 - 它等待一个新的工作有任何想法,为什么会发生?
require 'thread'
begin
require 'fastthread'
rescue LoadError
$stderr.puts "Using the ruby-core thread implementation"
end
class ThreadPool
class Worker
def initialize(callback)
@mutex = Mutex.new
@cv = ConditionVariable.new
@callback = callback
@mutex.synchronize {@running = true}
@thread = Thread.new do
while @mutex.synchronize {@running}
block = get_block
if block
block.call
reset_block
# Signal the ThreadPool that this worker is ready for another job
@callback.signal
else
# Wait for a new job
@mutex.synchronize …Run Code Online (Sandbox Code Playgroud)