Class: Spectator::AtomicNumber

Inherits:
Object
  • Object
show all
Defined in:
lib/spectator/atomic_number.rb

Overview

Thread safe number operations

Instance Method Summary collapse

Constructor Details

#initialize(init) ⇒ AtomicNumber

Returns a new instance of AtomicNumber.



4
5
6
7
# File 'lib/spectator/atomic_number.rb', line 4

def initialize(init)
  @value = init
  @lock = Mutex.new
end

Instance Method Details

#add_and_get(amount) ⇒ Object



33
34
35
# File 'lib/spectator/atomic_number.rb', line 33

def add_and_get(amount)
  @lock.synchronize { @value += amount }
end

#getObject



13
14
15
# File 'lib/spectator/atomic_number.rb', line 13

def get
  @lock.synchronize { @value }
end

#get_and_add(amount) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/spectator/atomic_number.rb', line 25

def get_and_add(amount)
  @lock.synchronize do
    tmp = @value
    @value += amount
    tmp
  end
end

#get_and_set(value) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/spectator/atomic_number.rb', line 17

def get_and_set(value)
  @lock.synchronize do
    tmp = @value
    @value = value
    tmp
  end
end

#max(value) ⇒ Object



37
38
39
40
41
42
43
# File 'lib/spectator/atomic_number.rb', line 37

def max(value)
  v = value.to_f
  @lock.synchronize do
    @value = v if v > @value || @value.nan?
  end
  @value
end

#set(value) ⇒ Object



9
10
11
# File 'lib/spectator/atomic_number.rb', line 9

def set(value)
  @lock.synchronize { @value = value }
end

#to_sObject



45
46
47
# File 'lib/spectator/atomic_number.rb', line 45

def to_s
  "AtomicNumber{#{@value}}"
end