Class: CountDownLatch

Inherits:
Object
  • Object
show all
Defined in:
lib/countdownlatch.rb,
lib/countdownlatch/version.rb

Overview

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

Mirrors the Java implementation: download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CountDownLatch.html

Examples:

Count down from 2 in 2 seconds, with a timeout of 10 seconds

latch = CountDownLatch.new 2

Thread.new do
  2.times do
    sleep 1
    latch.countdown!
  end
end

latch.wait 10

Author:

Constant Summary

VERSION =
"1.0.0"

Instance Method Summary collapse

Constructor Details

#initialize(count) ⇒ CountDownLatch

Create a new CountDownLatch

Raises:

  • (ArgumentError)

    if the count is less than zero



33
34
35
36
37
38
# File 'lib/countdownlatch.rb', line 33

def initialize(count)
  raise ArgumentError if count < 0
  @count = count
  @mutex = Mutex.new
  @conditional = ConditionVariable.new
end

Instance Method Details

#countInteger

Returns the current count. This method is typically used for debugging and testing purposes.



58
59
60
# File 'lib/countdownlatch.rb', line 58

def count
  @mutex.synchronize { @count }
end

#countdown!Object

Decrements the count of the latch, releasing all waiting threads if the count reaches zero.

  • If the current count is greater than zero then it is decremented. If the new count is zero then all waiting threads are re-enabled for thread scheduling purposes.

  • If the current count equals zero then nothing happens.



45
46
47
48
49
50
# File 'lib/countdownlatch.rb', line 45

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

#to_sString

Returns a string identifying this latch, as well as its state. The state, in brackets, includes the String “Count =” followed by the current count.



67
68
69
# File 'lib/countdownlatch.rb', line 67

def to_s
  super.insert -2, " (Count = #{count})"
end

#wait(timeout = nil) ⇒ Boolean

Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted. If the current count is zero then this method returns immediately. If the current count is greater than zero then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of three things happen:

  • The count reaches zero due to invocations of the countdown! method; or

  • Some other thread interrupts the current thread; or

  • The specified waiting time elapses.



83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/countdownlatch.rb', line 83

def wait(timeout = nil)
  begin
    Timeout::timeout timeout do
      @mutex.synchronize do
        @conditional.wait @mutex if @count > 0
      end
    end
    true
  rescue Timeout::Error
    false
  end
end