Class: AtomicRuby::Atom
- Inherits:
-
Object
- Object
- AtomicRuby::Atom
- Defined in:
- lib/atomic-ruby/atom.rb,
ext/atomic_ruby/atomic_ruby.c
Overview
This class is Ractor-safe in Ruby 4.0+ when compiled with ractor support. Values that cross ractor boundaries are automatically made shareable.
Provides atomic reference semantics using Compare-And-Swap (CAS) operations.
An Atom allows for lock-free, thread-safe updates to a single reference value. The core operation is #swap, which atomically updates the value based on the current value, retrying if another thread modifies it concurrently.
Instance Method Summary collapse
-
#initialize(value) ⇒ Atom
constructor
Creates a new atomic reference with the given initial value.
-
#swap {|current_value| ... } ⇒ untyped
Atomically updates the value using a compare-and-swap operation.
-
#value ⇒ untyped
Returns the current value stored in the atom.
Constructor Details
#initialize(value) ⇒ Atom
Creates a new atomic reference with the given initial value.
45 46 47 |
# File 'lib/atomic-ruby/atom.rb', line 45 def initialize(value) _initialize(value) end |
Instance Method Details
#swap {|current_value| ... } ⇒ untyped
Atomically updates the value using a compare-and-swap operation.
The block receives the current value and must return the new value. If another thread modifies the atom between reading the current value and attempting to update it, the operation retries with the new current value.
92 93 94 95 96 |
# File 'lib/atomic-ruby/atom.rb', line 92 def swap(&block) _swap do |old_value| make_shareable_if_needed(block.call(old_value)) end end |
#value ⇒ untyped
Returns the current value stored in the atom.
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.
62 63 64 |
# File 'lib/atomic-ruby/atom.rb', line 62 def value _value end |