Write an atomic operation Write an atomic operation ruby ruby

Write an atomic operation


It really depends on the scope you are interested in as to the right tools for the job. If you are looking to perform an atomic operation on a database, then the database driver will probably (if it's any good/the database supports it) offer a way to use a database transaction to make updates atomic.

If you are talking about a multi-threaded Ruby application attempting to makes updates to shared resources atomic and thread-safe, then Ruby provides the Mutex and ConditionVariable classes to help you out in that regard.(More info: http://ruby-doc.org/docs/ProgrammingRuby/html/tut_threads.html)


As you point to an article about databases, I'm guessing you are asking in this context.

If you are using Rails, you use the transaction methods of ActiveRecord.

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

If using outside of Rails, you have to work with what the database driver library provides. Check the implementation of transaction on Rails to get an idea of how it can be done.


The Mutex class is available in the 1.9 runtime (and require('thread') in 1.8) and allows you to lock operations in a context.

# Typically defined in the object initializer@lock = Mutex.new# Then in your code@lock.synchronize do  a += 10  b -= 39end

This will guarantee you that the block given to Mutex#synchronize is run sequentially.

Official doc is here: http://rubydoc.info/stdlib/core/1.9.2/Mutex