Class: Concurrent::MutexAtomicFixnum

Inherits:
Object
  • Object
show all
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

AtomicFixnum

Instance Method Summary collapse

Constructor Details

#initialize(init = 0) ⇒ MutexAtomicFixnum

Creates a new ‘AtomicFixnum` with the given initial value.

Parameters:

  • init (Fixnum) (defaults to: 0)

    the initial value

Raises:

  • (ArgumentError)

    if the initial value is not a ‘Fixnum`

Since:

  • 0.5.0



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.

Parameters:

  • expect (Fixnum)

    the expected value

  • update (Fixnum)

    the new value

Returns:

  • (Boolean)

    true if the value was updated else false

Since:

  • 0.5.0



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

#decrementFixnum Also known as: down

Decreases the current value by 1.

Returns:

  • (Fixnum)

    the current value after decrementation

Since:

  • 0.5.0



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

#incrementFixnum Also known as: up

Increases the current value by 1.

Returns:

  • (Fixnum)

    the current value after incrementation

Since:

  • 0.5.0



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

#valueFixnum

Retrieves the current ‘Fixnum` value.

Returns:

  • (Fixnum)

    the current value

Since:

  • 0.5.0



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.

Parameters:

  • value (Fixnum)

    the new value to be set

Returns:

  • (Fixnum)

    the current value

Raises:

  • (ArgumentError)

    if the new value is not a ‘Fixnum`

Since:

  • 0.5.0



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