Class: WaitGroup

Inherits:
Object
  • Object
show all
Defined in:
lib/channel/waitgroup.rb

Instance Method Summary collapse

Constructor Details

#initializeWaitGroup

Returns a new instance of WaitGroup.



2
3
4
5
6
# File 'lib/channel/waitgroup.rb', line 2

def initialize
  @mutex = Mutex.new
  @count = 0
  @waiting = []
end

Instance Method Details

#add(delta) ⇒ Object



8
9
10
11
12
13
14
15
16
17
# File 'lib/channel/waitgroup.rb', line 8

def add(delta)
  sync! do
    @count += delta
    fail 'negative WaitGroup counter' if @count < 0
    if @waiting.any? && delta > 0 && @count == delta
      fail 'misuse: add called concurrently with wait'
    end
    wake!
  end
end

#doneObject



19
20
21
# File 'lib/channel/waitgroup.rb', line 19

def done
  add(-1)
end

#waitObject



27
28
29
30
31
32
# File 'lib/channel/waitgroup.rb', line 27

def wait
  sync! do
    @waiting << Thread.current
    @mutex.sleep until done?
  end
end