Class: Redstruct::Utils::AtomicCounter
- Inherits:
-
Object
- Object
- Redstruct::Utils::AtomicCounter
- Defined in:
- lib/redstruct/utils/atomic_counter.rb
Overview
Very basic utility class to have thread-safe counters
Instance Method Summary collapse
-
#decrement(by: 1) ⇒ Integer
Decrements the counter by the given delta.
-
#increment(by: 1) ⇒ Integer
Increments the counter by the given delta.
-
#initialize(initial = 0) ⇒ AtomicCounter
constructor
A new instance of AtomicCounter.
Constructor Details
#initialize(initial = 0) ⇒ AtomicCounter
Returns a new instance of AtomicCounter.
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
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
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 |