require "ev/ruby" require "thread" class FakeThread def initialize(*args) yield(*args) end def join end end class ThreadLimiter def initialize(limit) @limit = limit @count = 0 @threads = [] @mutex = Mutex.new @cv = ConditionVariable.new every(1) do @mutex.synchronize do @threads.dup.each do |t| unless t.alive? $stderr.puts "Found dead thread." @threads.delete(t) @count -= 1 @cv.signal end end end end end def wait if block_given? self.wait yield self.signal else @mutex.synchronize do @threads << Thread.current @count += 1 @cv.wait(@mutex) if @count > @limit end end end def signal @mutex.synchronize do @threads.delete(Thread.current) @count -= 1 @cv.signal end end end