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() { || ... } click to toggle source

Execute maximum number of threads in parallel.

# File lib/tins/limited.rb, line 19
def execute
  @mutex.synchronize do
    loop do
      if @count < @maximum
        @count += 1
        Thread.new do
          @tg.add Thread.current
          yield
          @mutex.synchronize { @count -= 1 }
          @continue.signal
        end
        return
      else
        @continue.wait(@mutex)
      end
    end
  end
end
process() { |self| ... } click to toggle source
# File lib/tins/limited.rb, line 42
def process
  yield self
ensure
  wait
end
wait() click to toggle source
# File lib/tins/limited.rb, line 38
def wait
  @tg.list.each(&:join)
end