Class: Tins::Limited
Instance Attribute Summary collapse
-
#maximum ⇒ Object
readonly
The maximum number of worker threads.
Instance Method Summary collapse
-
#execute ⇒ Object
Execute maximum number of threads in parallel.
-
#initialize(maximum) ⇒ Limited
constructor
Create a Limited instance, that runs maximum threads at most.
- #process ⇒ Object
- #wait ⇒ Object
Constructor Details
#initialize(maximum) ⇒ Limited
Create a Limited instance, that runs maximum threads at most.
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
#maximum ⇒ Object (readonly)
The maximum number of worker threads.
16 17 18 |
# File 'lib/tins/limited.rb', line 16 def maximum @maximum end |
Instance Method Details
#execute ⇒ Object
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 |
#process ⇒ Object
42 43 44 45 46 |
# File 'lib/tins/limited.rb', line 42 def process yield self ensure wait end |
#wait ⇒ Object
38 39 40 |
# File 'lib/tins/limited.rb', line 38 def wait @tg.list.each(&:join) end |