Class: Garcon::AtomicMutex

Inherits:
Object show all
Includes:
AtomicDirectUpdate, AtomicNumericCompareAndSetWrapper
Defined in:
lib/garcon/task/atomic.rb

Instance Method Summary collapse

Methods included from AtomicNumericCompareAndSetWrapper

#compare_and_set

Methods included from AtomicDirectUpdate

#try_update, #update

Constructor Details

#initialize(value = nil) ⇒ AtomicMutex

Returns a new instance of AtomicMutex.



87
88
89
90
# File 'lib/garcon/task/atomic.rb', line 87

def initialize(value = nil)
  @mutex = Mutex.new
  @value = value
end

Instance Method Details

#_compare_and_set(old_value, new_value) ⇒ Boolean

Atomically sets the value to the given updated value if the current value is equal the expected value.

Parameters:

  • old_value (Object)

    The expected value.

  • new_value (Object)

    The new value.

Returns:

  • (Boolean)

    ‘true` if successful, `false` indicates that the actual value was not equal to the expected value.



140
141
142
143
144
145
146
147
148
149
# File 'lib/garcon/task/atomic.rb', line 140

def _compare_and_set(old_value, new_value)
  return false unless @mutex.try_lock
  begin
    return false unless @value.equal? old_value
    @value = new_value
  ensure
    @mutex.unlock
  end
  true
end

#getObject Also known as: value

Gets the current value.

Returns:

  • (Object)

    The current value.



96
97
98
# File 'lib/garcon/task/atomic.rb', line 96

def get
  @mutex.synchronize { @value }
end

#get_and_set(new_value) ⇒ Object Also known as: swap

Atomically sets to the given value and returns the old value.

Parameters:

  • value (Object)

    The new value to set.

Returns:



120
121
122
123
124
125
126
# File 'lib/garcon/task/atomic.rb', line 120

def get_and_set(new_value)
  @mutex.synchronize do
    old_value = @value
    @value = new_value
    old_value
  end
end

#set(value) ⇒ Object Also known as: value=

Sets to the given value.

Parameters:

  • value (Object)

    The new value to set.

Returns:



108
109
110
# File 'lib/garcon/task/atomic.rb', line 108

def set(value)
  @mutex.synchronize { @value = value }
end