Class: AtomicCounter::Counter

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(start = 0) ⇒ Counter

Returns a new instance of Counter.



5
6
7
8
9
# File 'lib/atomic_counter/counter.rb', line 5

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

Instance Attribute Details

#currentObject (readonly)

Returns the value of attribute current.



3
4
5
# File 'lib/atomic_counter/counter.rb', line 3

def current
  @current
end

Instance Method Details

#decrement(by = 1) ⇒ Object



17
18
19
20
21
# File 'lib/atomic_counter/counter.rb', line 17

def decrement(by = 1)
  @mutex.synchronize do
    @current -= by
  end
end

#increment(by = 1) ⇒ Object



11
12
13
14
15
# File 'lib/atomic_counter/counter.rb', line 11

def increment(by = 1)
  @mutex.synchronize do
    @current += by
  end
end

#resetObject



23
24
25
26
27
28
29
# File 'lib/atomic_counter/counter.rb', line 23

def reset
  @mutex.synchronize do
    local_value = @current
    @current = @initial
    local_value
  end
end