class Tins::Limited

Attributes

maximum[R]

The maximum number of worker threads.

Public Class Methods

new(maximum) click to toggle source

Create a Limited instance, that runs maximum threads at most.

# 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

Public Instance Methods

execute(&block) click to toggle source

Execute maximum number of threads in parallel.

# File lib/tins/limited.rb, line 19
def execute(&block)
  @tasks or raise ArgumentError, "start processing first"
  @tasks << block
end
process() { |self| ... } click to toggle 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
stop() click to toggle source
# File lib/tins/limited.rb, line 37
def stop
  throw :stop
end

Private Instance Methods

create_executor() click to toggle 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
done?() click to toggle source
# File lib/tins/limited.rb, line 43
def done?
  @tasks.empty? && @tg.list.empty?
end
wait() click to toggle source
# File lib/tins/limited.rb, line 47
def wait
  @tg.list.each(&:join)
end