views:

112

answers:

4

Hi,

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

For instance, if I have:

a = 30
b = 75

I would like to be able to do something like:

atomic_operation do
  a += 10
  b -= 39
end

Is there a native module in Ruby 1.9 that allow such process? If possible, I would like to do so without using a plugin. Many thanks!

+4  A: 

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)

fd
Also check out the `Monitor` and `MonitorMixin` classes that are part of the Ruby standard libraries.
Lars Haugseth
+2  A: 

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.

Chubas
+1  A: 

What you need my friend is a Software transactional memory. Try out the STM implementation I have been playing with in JRuby (You need to checkout the code in repo as I haven't packaged it for the release).

Also check out Ruby atomic I am working on http://github.com/saivenkat/ruby-atomic. Gives you CAS type of operations on MRI. This is a bit lower level but will help you with the same problem. I haven't written Transactional Memory for MRI one but with the CAS infrastructure it won't be long :)

P.S Stackoverflow doesn't let me post more than one link as I didn't use its system a lot. So checkout the multiverse site in codehaus for STM in JRuby

--Sai Venkat

Sai Venkat
+1 for STM being what the OP needs. Haven't tried the library though.
Isaac Cambron
A: 

Have you had a look at the 'Transaction Simple' gem?

I think that would suit your purpose

http://rubyforge.org/projects/trans-simple

globetrotter