Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Ruby have atomic variables?

Tags:

ruby

Does Ruby have atomic variables, like AtomicInteger or AtomicBoolean in Java?

like image 492
michal Avatar asked Aug 15 '12 15:08

michal


3 Answers

Here is a gem that might provide what you need (found linked from here). The code is clean and compact enough to quickly understand (it is basically a Mutex, as everyone else has suggested), which should give you a good starting point if you want to write your own Mutex wrapper.

A lightly modified example from github:

require 'atomic'

my_atomic = Atomic.new('')

# set method 1:
my_atomic.update { |v| v + 'hello' }

# set method 2:
begin
  my_atomic.try_update { |v| v + 'world' }
rescue Atomic::ConcurrentUpdateError => cue
  # deal with it (retry, propagate, etc)
end

# access with:
puts my_atomic.value
like image 112
tsundoku Avatar answered Nov 04 '22 22:11

tsundoku


It should be noted that implementing atomic types in terms of mutexes defeats the purpose of using the 'atomic' abstraction.

Proper atomic implementations emit code that leverages CPU's compare-and-swap instruction.

like image 45
deprecated Avatar answered Nov 04 '22 20:11

deprecated


Use Mutex as suggested like so:

i = 0
lock = Mutex.new

# Then whenever you want to modify it:
lock.synchronize do
  i += 1
end
like image 28
Travis Reeder Avatar answered Nov 04 '22 22:11

Travis Reeder