Class: AtomicRuby::AtomicCountDownLatch
- Inherits:
-
Object
- Object
- AtomicRuby::AtomicCountDownLatch
- Defined in:
- lib/atomic-ruby/atomic_count_down_latch.rb
Overview
This class is Ractor-safe in Ruby 4.0+ when compiled with ractor support.
Provides a countdown synchronization primitive using atomic operations.
AtomicCountDownLatch is a synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. The latch is initialized with a count, and threads can wait for the count to reach zero or decrement the count atomically.
Defined Under Namespace
Classes: AlreadyCountedDownError, Error
Instance Method Summary collapse
-
#count ⇒ Integer
Returns the current count value.
-
#count_down ⇒ Integer
Atomically decrements the count by one.
-
#initialize(count) ⇒ AtomicCountDownLatch
constructor
Creates a new countdown latch with the specified count.
-
#wait ⇒ void
Blocks the current thread until the count reaches zero.
Constructor Details
#initialize(count) ⇒ AtomicCountDownLatch
Creates a new countdown latch with the specified count.
67 68 69 70 71 72 73 74 75 |
# File 'lib/atomic-ruby/atomic_count_down_latch.rb', line 67 def initialize(count) unless count.is_a?(Integer) && count > 0 raise ArgumentError, "count must be a positive Integer" end @count = Atom.new(count) Ractor.make_shareable(self) if RACTOR_SAFE end |
Instance Method Details
#count ⇒ Integer
Returns the current count value.
This operation is atomic and thread-safe. The returned value reflects the state at the time of the call, but may change immediately after in concurrent environments.
92 93 94 |
# File 'lib/atomic-ruby/atomic_count_down_latch.rb', line 92 def count @count.value end |
#count_down ⇒ Integer
Atomically decrements the count by one.
If the count reaches zero, any threads waiting on #wait will be unblocked. This operation uses compare-and-swap to ensure atomicity and prevent race conditions.
119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
# File 'lib/atomic-ruby/atomic_count_down_latch.rb', line 119 def count_down already_counted_down = false new_count = @count.swap do |current_count| if current_count == 0 already_counted_down = true current_count else current_count - 1 end end raise AlreadyCountedDownError, "already counted down to zero" if already_counted_down new_count end |
#wait ⇒ void
This method returns an undefined value.
Blocks the current thread until the count reaches zero.
This method will block the calling thread until other threads have called #count_down enough times to reduce the count to zero. The method uses busy-waiting (Thread.pass) to check the count.
168 169 170 |
# File 'lib/atomic-ruby/atomic_count_down_latch.rb', line 168 def wait Thread.pass while @count.value > 0 end |