Class: Contender::CountdownLatch

Inherits:
Object
  • Object
show all
Defined in:
lib/contender/countdown_latch.rb

Overview

Synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads complete

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(initial) ⇒ undefined

Parameters:

  • initial (Integer)

Raises:

  • (ArgumentError)


10
11
12
13
14
15
16
17
# File 'lib/contender/countdown_latch.rb', line 10

def initialize(initial)
  raise ArgumentError if initial < 0

  @count = initial

  @mutex = Mutex.new
  @condition = ConditionVariable.new
end

Instance Attribute Details

#countInteger (readonly)

Returns:

  • (Integer)


6
7
8
# File 'lib/contender/countdown_latch.rb', line 6

def count
  @count
end

Instance Method Details

#await(timeout = nil) ⇒ Boolean

Waits until either the latch reaches zero or the timeout is reached

Parameters:

  • timeout (Float) (defaults to: nil)

Returns:

  • (Boolean)

    True if the latch reached zero, false if the timeout was reached



35
36
37
38
39
40
41
42
# File 'lib/contender/countdown_latch.rb', line 35

def await(timeout = nil)
  @mutex.synchronize do
    return true if @count == 0
    @condition.wait @mutex, timeout

    @count == 0
  end
end

#countdownundefined

Performs an ordered decrement operation for this latch

Returns:

  • (undefined)


23
24
25
26
27
28
# File 'lib/contender/countdown_latch.rb', line 23

def countdown
  @mutex.synchronize do
    @count -= 1 if @count > 0
    @condition.broadcast if @count == 0
  end
end