Class: Zookeeper::Latch

Inherits:
Object
  • Object
show all
Defined in:
lib/zookeeper/latch.rb

Overview

a cross-thread gate of sorts.

Instance Method Summary collapse

Constructor Details

#initialize(count = 1) ⇒ Latch

Returns a new instance of Latch.



4
5
6
7
8
# File 'lib/zookeeper/latch.rb', line 4

def initialize(count = 1)
  @count = count
  @mutex = Monitor.new
  @cond = @mutex.new_cond
end

Instance Method Details

#await(timeout = nil) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/zookeeper/latch.rb', line 17

def await(timeout=nil)
  @mutex.synchronize do
    if timeout
      time_to_stop = Time.now + timeout

      while @count > 0
        @cond.wait(timeout)
        
        break if (Time.now > time_to_stop)
      end
    else
      @cond.wait_while { @count > 0 }
    end
  end
end

#releaseObject



10
11
12
13
14
15
# File 'lib/zookeeper/latch.rb', line 10

def release
  @mutex.synchronize {
    @count -= 1 if @count > 0
    @cond.broadcast if @count.zero?
  }
end