Class: Concurrent::MutexCountDownLatch
- Inherits:
-
Object
- Object
- Concurrent::MutexCountDownLatch
- Defined in:
- lib/concurrent/atomic/count_down_latch.rb
Overview
A synchronization object that allows one thread to wait on multiple other threads. The thread that will wait creates a CountDownLatch and sets the initial value (normally equal to the number of other threads). The initiating thread passes the latch to the other threads then waits for the other threads by calling the #wait method. Each of the other threads calls #count_down when done with its work. When the latch counter reaches zero the waiting thread is unblocked and continues with its work. A CountDownLatch can be used only once. Its value cannot be reset.
Direct Known Subclasses
Instance Method Summary collapse
-
#count ⇒ Fixnum
The current value of the counter.
-
#count_down ⇒ Object
Signal the latch to decrement the counter.
-
#initialize(count) ⇒ MutexCountDownLatch
constructor
Create a new
CountDownLatchwith the initialcount. -
#wait(timeout = nil) ⇒ Boolean
Block on the latch until the counter reaches zero or until
timeoutis reached.
Constructor Details
#initialize(count) ⇒ MutexCountDownLatch
Create a new CountDownLatch with the initial count.
23 24 25 26 27 28 29 30 |
# File 'lib/concurrent/atomic/count_down_latch.rb', line 23 def initialize(count) unless count.is_a?(Fixnum) && count >= 0 raise ArgumentError.new('count must be in integer greater than or equal zero') end @mutex = Mutex.new @condition = Condition.new @count = count end |
Instance Method Details
#count ⇒ Fixnum
The current value of the counter.
67 68 69 |
# File 'lib/concurrent/atomic/count_down_latch.rb', line 67 def count @mutex.synchronize { @count } end |
#count_down ⇒ Object
Signal the latch to decrement the counter. Will signal all blocked threads when the count reaches zero.
55 56 57 58 59 60 |
# File 'lib/concurrent/atomic/count_down_latch.rb', line 55 def count_down @mutex.synchronize do @count -= 1 if @count > 0 @condition.broadcast if @count == 0 end end |
#wait(timeout = nil) ⇒ Boolean
Block on the latch until the counter reaches zero or until timeout is reached.
39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/concurrent/atomic/count_down_latch.rb', line 39 def wait(timeout = nil) @mutex.synchronize do remaining = Condition::Result.new(timeout) while @count > 0 && remaining.can_wait? remaining = @condition.wait(@mutex, remaining.remaining_time) end @count == 0 end end |