Class: WaterDrop::Helpers::Counter

Inherits:
Object
  • Object
show all
Defined in:
lib/waterdrop/helpers/counter.rb

Overview

Atomic counter that we can safely increment and decrement without race conditions

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCounter

Creates a new counter initialized to 0



12
13
14
15
# File 'lib/waterdrop/helpers/counter.rb', line 12

def initialize
  @value = 0
  @mutex = Mutex.new
end

Instance Attribute Details

#valueInteger (readonly)

Returns current value.

Returns:

  • (Integer)

    current value



9
10
11
# File 'lib/waterdrop/helpers/counter.rb', line 9

def value
  @value
end

Instance Method Details

#decrementObject

Decrements the value by 1



23
24
25
# File 'lib/waterdrop/helpers/counter.rb', line 23

def decrement
  @mutex.synchronize { @value -= 1 }
end

#incrementObject

Increments the value by 1



18
19
20
# File 'lib/waterdrop/helpers/counter.rb', line 18

def increment
  @mutex.synchronize { @value += 1 }
end