Class: Hx::Interop::TaskGroup

Inherits:
Object
  • Object
show all
Defined in:
lib/interop/task_group.rb

Overview

Allows blocking on running tasks

Instance Method Summary collapse

Constructor Details

#initializeTaskGroup

Returns a new instance of TaskGroup.



5
6
7
8
9
# File 'lib/interop/task_group.rb', line 5

def initialize
  @count     = 0
  @mutex     = Mutex.new
  @condition = ConditionVariable.new
end

Instance Method Details

#runObject

Run the given block in a new thread. Calls to #wait will block until it has finished running.



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/interop/task_group.rb', line 12

def run
  @mutex.synchronize { @count += 1 }
  Thread.new do
    yield
  ensure
    @mutex.synchronize do
      @count -= 1
      @condition.broadcast if @count.zero?
    end
  end
end

#waitObject

Block until all threads created by #run have finished.



25
26
27
28
29
# File 'lib/interop/task_group.rb', line 25

def wait
  @mutex.synchronize do
    @condition.wait(@mutex) while @count.positive?
  end
end