michal
michal

Reputation: 381

Does Ruby have atomic variables?

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

Upvotes: 16

Views: 5329

Answers (5)

Travis Reeder
Travis Reeder

Reputation: 41123

Use Mutex as suggested like so:

i = 0
lock = Mutex.new

# Then whenever you want to modify it:
lock.synchronize do
  i += 1
end

Upvotes: 5

deprecated
deprecated

Reputation: 5242

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.

Upvotes: 8

Edd Morgan
Edd Morgan

Reputation: 2923

Not natively, but you can get some atomicity using the Mutex class.

You could probably implement your own AtomicString, for example, using a Mutex.

Upvotes: 1

tsundoku
tsundoku

Reputation: 1350

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

Upvotes: 9

davidrac
davidrac

Reputation: 10738

I don't think that Ruby has one. However, there is a Mutex you can use to imitate one.

Upvotes: 1

Related Questions