Class: Redstruct::Utils::AtomicCounter

Inherits:
Object
  • Object
show all
Defined in:
lib/redstruct/utils/atomic_counter.rb

Overview

Very basic utility class to have thread-safe counters

Instance Method Summary collapse

Constructor Details

#initialize(initial = 0) ⇒ AtomicCounter

Returns a new instance of AtomicCounter.

Parameters:

  • initial (Integer) (defaults to: 0)

    the initial value of the counter



8
9
10
11
# File 'lib/redstruct/utils/atomic_counter.rb', line 8

def initialize(initial = 0)
  @lock = Mutex.new
  @current = initial
end

Instance Method Details

#decrement(by: 1) ⇒ Integer

Decrements the counter by the given delta

Parameters:

  • by (Integer) (defaults to: 1)

    the delta to decrement by

Returns:

  • (Integer)

    the new, decremented value



25
26
27
# File 'lib/redstruct/utils/atomic_counter.rb', line 25

def decrement(by: 1)
  return increment(by: -by.to_i)
end

#increment(by: 1) ⇒ Integer

Increments the counter by the given delta

Parameters:

  • by (Integer) (defaults to: 1)

    the delta to increment by

Returns:

  • (Integer)

    the new, incremented value



16
17
18
19
20
# File 'lib/redstruct/utils/atomic_counter.rb', line 16

def increment(by: 1)
  return @lock.synchronize do
    @current += by.to_i
  end
end