Class: Pandemic::MutexCounter
- Inherits:
-
Object
- Object
- Pandemic::MutexCounter
- Defined in:
- lib/pandemic/mutex_counter.rb
Constant Summary collapse
- MAX =
(2 ** 30) - 1
Instance Method Summary collapse
-
#decr ⇒ Object
(also: #pred, #prev)
decr only to zero.
- #inc ⇒ Object (also: #next, #succ)
-
#initialize(max = MAX) ⇒ MutexCounter
constructor
A new instance of MutexCounter.
- #real_total ⇒ Object (also: #to_i)
- #value ⇒ Object
Constructor Details
#initialize(max = MAX) ⇒ MutexCounter
Returns a new instance of MutexCounter.
4 5 6 7 8 9 |
# File 'lib/pandemic/mutex_counter.rb', line 4 def initialize(max = MAX) @mutex = Mutex.new @counter = 0 @resets = 0 @max = max end |
Instance Method Details
#decr ⇒ Object Also known as: pred, prev
decr only to zero
33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/pandemic/mutex_counter.rb', line 33 def decr @mutex.synchronize do if @counter > 0 @counter -= 1 else if @resets > 1 @resets -= 1 @counter = @max end end @counter end end |
#inc ⇒ Object Also known as: next, succ
20 21 22 23 24 25 26 27 28 |
# File 'lib/pandemic/mutex_counter.rb', line 20 def inc @mutex.synchronize do if @counter >= @max @counter = 0 # to avoid Bignum, it's about 4x slower @resets += 1 end @counter += 1 end end |
#real_total ⇒ Object Also known as: to_i
11 12 13 |
# File 'lib/pandemic/mutex_counter.rb', line 11 def real_total @mutex.synchronize { (@resets * @max) + @counter } end |
#value ⇒ Object
16 17 18 |
# File 'lib/pandemic/mutex_counter.rb', line 16 def value @mutex.synchronize { @counter } end |