Class: Pandemic::MutexCounter

Inherits:
Object
  • Object
show all
Defined in:
lib/pandemic/mutex_counter.rb

Constant Summary collapse

MAX =
(2 ** 30) - 1

Instance Method Summary collapse

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

#decrObject 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

#incObject 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_totalObject 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

#valueObject



16
17
18
# File 'lib/pandemic/mutex_counter.rb', line 16

def value
  @mutex.synchronize { @counter }
end