class Tins::Limited
Attributes
The maximum number of worker threads.
Public Class Methods
Source
# File lib/tins/limited.rb, line 6 def initialize(maximum) @mutex = Mutex.new @continue = ConditionVariable.new @maximum = Integer(maximum) raise ArgumentError, "maximum < 1" if @maximum < 1 @count = 0 @tg = ThreadGroup.new end
Create a Limited
instance, that runs maximum threads at most.
Public Instance Methods
Source
# File lib/tins/limited.rb, line 19 def execute(&block) @tasks or raise ArgumentError, "start processing first" @tasks << block end
Execute maximum number of threads in parallel.
Source
# File lib/tins/limited.rb, line 24 def process @tasks = Queue.new @executor = create_executor catch :stop do loop do yield self end ensure wait until done? @executor.kill end end
Private Instance Methods
Source
# File lib/tins/limited.rb, line 51 def create_executor Thread.new do @mutex.synchronize do loop do if @count < @maximum task = @tasks.pop @count += 1 Thread.new do @tg.add Thread.current task.(Thread.current) ensure @count -= 1 @continue.signal end else @continue.wait(@mutex) end end end end end