Class: AtomicRuby::Atom
- Inherits:
-
Object
- Object
- AtomicRuby::Atom
- Defined in:
- lib/atomic-ruby/atom.rb,
sig/generated/atomic-ruby/atom.rbs,
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.
-
#make_shareable_if_needed(value) ⇒ untyped
Makes a value shareable when crossing ractor boundaries.
-
#swap {|current_value, arg0| ... } ⇒ 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
#make_shareable_if_needed(value) ⇒ untyped
Makes a value shareable when crossing ractor boundaries.
This method ensures ractor safety by automatically making values shareable when they need to cross ractor boundaries in Ruby 4.0+.
109 110 111 112 113 114 115 116 |
# File 'lib/atomic-ruby/atom.rb', line 109 def make_shareable_if_needed(value) if RACTOR_SAFE && (_initialized_ractor.nil? || Ractor.current != _initialized_ractor) Ractor.make_shareable(value) else value end end |
#swap {|current_value, arg0| ... } ⇒ 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 |