michal michal - 1 year ago 78
Ruby Question

Does Ruby have atomic variables?

Does Ruby have atomic variables, like

in Java?

Answer Source

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:
  my_atomic.try_update { |v| v + 'world' }
rescue Atomic::ConcurrentUpdateError => cue
  # deal with it (retry, propagate, etc)

# access with:
puts my_atomic.value
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download