Class: AtomicRuby::AtomicBoolean
- Inherits:
-
Object
- Object
- AtomicRuby::AtomicBoolean
- Defined in:
- lib/atomic-ruby/atomic_boolean.rb
Overview
This class is Ractor-safe in Ruby 4.0+ when compiled with ractor support.
Provides atomic boolean semantics with thread-safe toggle operations.
AtomicBoolean wraps a boolean value in an atomic reference, providing lock-free operations for common boolean manipulations like toggling, setting to true/false, and checking the current state.
Instance Method Summary collapse
-
#false? ⇒ true, false
Tests if the current value is false.
-
#initialize(boolean) ⇒ AtomicBoolean
constructor
Creates a new atomic boolean with the given initial value.
-
#make_false ⇒ false
Atomically sets the value to false.
-
#make_true ⇒ true
Atomically sets the value to true.
-
#toggle ⇒ true, false
Atomically toggles the boolean value.
-
#true? ⇒ true, false
Tests if the current value is true.
-
#value ⇒ true, false
Returns the current boolean value stored in the atom.
Constructor Details
#initialize(boolean) ⇒ AtomicBoolean
Creates a new atomic boolean with the given initial value.
48 49 50 51 52 53 54 55 56 |
# File 'lib/atomic-ruby/atomic_boolean.rb', line 48 def initialize(boolean) unless boolean.is_a?(TrueClass) || boolean.is_a?(FalseClass) raise ArgumentError, "boolean must be a TrueClass or FalseClass" end @boolean = Atom.new(boolean) Ractor.make_shareable(self) if RACTOR_SAFE end |
Instance Method Details
#false? ⇒ true, false
Tests if the current value is false.
99 100 101 |
# File 'lib/atomic-ruby/atomic_boolean.rb', line 99 def false? value == false end |
#make_false ⇒ false
Atomically sets the value to false.
This operation uses compare-and-swap to ensure atomicity, making it safe for concurrent access.
133 134 135 |
# File 'lib/atomic-ruby/atomic_boolean.rb', line 133 def make_false @boolean.swap { false } end |
#make_true ⇒ true
Atomically sets the value to true.
This operation uses compare-and-swap to ensure atomicity, making it safe for concurrent access.
116 117 118 |
# File 'lib/atomic-ruby/atomic_boolean.rb', line 116 def make_true @boolean.swap { true } end |
#toggle ⇒ true, false
Atomically toggles the boolean value.
Changes true to false and false to true using a compare-and-swap operation, making it safe for concurrent access from multiple threads.
154 155 156 |
# File 'lib/atomic-ruby/atomic_boolean.rb', line 154 def toggle @boolean.swap { |current_value| !current_value } end |
#true? ⇒ true, false
Tests if the current value is true.
85 86 87 |
# File 'lib/atomic-ruby/atomic_boolean.rb', line 85 def true? value == true end |
#value ⇒ true, false
Returns the current boolean 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.
71 72 73 |
# File 'lib/atomic-ruby/atomic_boolean.rb', line 71 def value @boolean.value end |