Write atomic operation

I would like to execute some atomicity methods with Ruby, according to http://en.wikipedia.org/wiki/Atomicity_(database_systems)

For example, if I have:

a = 30
b = 75

I would like to do something like:

atomic_operation do
  a += 10
  b -= 39
end

Is there a built-in module in Ruby 1.9 that allows this process? If possible, I would like to do this without using a plugin. Many thanks!

+5
source share
5 answers

, . , , , ( / ) .

Ruby, , Ruby Mutex ConditionVariable, . ( : http://ruby-doc.org/docs/ProgrammingRuby/html/tut_threads.html)

+7

Mutex 1.9 ( require('thread') 1.8) .

# Typically defined in the object initializer
@lock = Mutex.new

# Then in your code
@lock.synchronize do
  a += 10
  b -= 39
end

, , Mutex #, .

: http://rubydoc.info/stdlib/core/1.9.2/Mutex

+6

, , .

Rails, transaction ActiveRecord.

Account.transaction do
  @alice.withdraw!(100)
  @bob.deposit!(100)
end

Rails , . Rails, , .

+4

, - . STM, JRuby ( , ).

Ruby atomic. http://github.com/saivenkat/ruby-atomic. CAS MRI. , . Transactional Memory MRI, CAS :)

P.SStackoverflow , . , Codehaus STM JRuby

-

+2

All Articles