Class: Tins::Limited

Inherits:
Object show all
Defined in:
lib/tins/limited.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(maximum) ⇒ Limited

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

Raises:

  • (ArgumentError)


6
7
8
9
10
11
12
13
# 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

Instance Attribute Details

#maximumObject (readonly)

The maximum number of worker threads.



16
17
18
# File 'lib/tins/limited.rb', line 16

def maximum
  @maximum
end

Instance Method Details

#executeObject

Execute maximum number of threads in parallel.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# 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

#processObject



42
43
44
45
46
# File 'lib/tins/limited.rb', line 42

def process
  yield self
ensure
  wait
end

#waitObject



38
39
40
# File 'lib/tins/limited.rb', line 38

def wait
  @tg.list.each(&:join)
end