Class: Concurrent::MutexAtomicFixnum
- Inherits:
-
Object
- Object
- Concurrent::MutexAtomicFixnum
- Defined in:
- lib/concurrent/atomic/atomic_fixnum.rb
Overview
A numeric value that can be updated atomically. Reads and writes to an atomic fixnum and thread-safe and guaranteed to succeed. Reads and writes may block briefly but no explicit locking is required.
Direct Known Subclasses
Instance Method Summary collapse
-
#compare_and_set(expect, update) ⇒ Boolean
Atomically sets the value to the given updated value if the current value == the expected value.
-
#decrement ⇒ Fixnum
(also: #down)
Decreases the current value by 1.
-
#increment ⇒ Fixnum
(also: #up)
Increases the current value by 1.
-
#initialize(init = 0) ⇒ MutexAtomicFixnum
constructor
Creates a new ‘AtomicFixnum` with the given initial value.
-
#value ⇒ Fixnum
Retrieves the current ‘Fixnum` value.
-
#value=(value) ⇒ Fixnum
Explicitly sets the value.
Constructor Details
#initialize(init = 0) ⇒ MutexAtomicFixnum
Creates a new ‘AtomicFixnum` with the given initial value.
19 20 21 22 23 |
# File 'lib/concurrent/atomic/atomic_fixnum.rb', line 19 def initialize(init = 0) raise ArgumentError.new('initial value must be a Fixnum') unless init.is_a?(Fixnum) @value = init @mutex = Mutex.new end |
Instance Method Details
#compare_and_set(expect, update) ⇒ Boolean
Atomically sets the value to the given updated value if the current value == the expected value.
91 92 93 94 95 96 97 98 99 100 101 |
# File 'lib/concurrent/atomic/atomic_fixnum.rb', line 91 def compare_and_set(expect, update) @mutex.lock if @value == expect @value = update true else false end ensure @mutex.unlock end |
#decrement ⇒ Fixnum Also known as: down
Decreases the current value by 1.
73 74 75 76 77 78 |
# File 'lib/concurrent/atomic/atomic_fixnum.rb', line 73 def decrement @mutex.lock @value -= 1 ensure @mutex.unlock end |
#increment ⇒ Fixnum Also known as: up
Increases the current value by 1.
59 60 61 62 63 64 |
# File 'lib/concurrent/atomic/atomic_fixnum.rb', line 59 def increment @mutex.lock @value += 1 ensure @mutex.unlock end |
#value ⇒ Fixnum
Retrieves the current ‘Fixnum` value.
30 31 32 33 34 35 |
# File 'lib/concurrent/atomic/atomic_fixnum.rb', line 30 def value @mutex.lock @value ensure @mutex.unlock end |
#value=(value) ⇒ Fixnum
Explicitly sets the value.
46 47 48 49 50 51 52 |
# File 'lib/concurrent/atomic/atomic_fixnum.rb', line 46 def value=(value) raise ArgumentError.new('value must be a Fixnum') unless value.is_a?(Fixnum) @mutex.lock @value = value ensure @mutex.unlock end |