coderrr

December 5, 2008

Quick thread safe incrementing in MRI

Filed under: ruby — coderrr @ 7:41 pm

Here’s a stupid little hack that just crossed my mind.

If you ever needed keep a counter which you incremented by 1 from multiple threads and you wanted to save yourself from having to wrap the increment in a Mutex because you were super anal about speed and you are using MRI (not jruby or rubinius)… then instead of:

@counter = 0
...
@mutex.synchronize { @counter += 1 }

you could do:

@counter = '0'
...
@counter.succ!
...
@counter.to_i

Since String#succ! is just a C function it’ll be thread safe. But that’s probably only guaranteed in MRI. Any other VM could have an implementation of succ! which is pre-emptable.

In my benchmarks its about 20x faster.

2 Comments »

  1. The C-implementation for String#succ! is:

    rb_str_shared_replace(str, rb_str_succ(str));

    That doesn’t look thread-safe to me. :)

    Comment by Per Velschow — December 6, 2008 @ 12:21 am

  2. It’s thread safe because MRI uses green threads and therefore won’t switch threads in the middle of a native C function.

    Like I said in other VMs all bets are off.

    Comment by coderrr — December 6, 2008 @ 7:35 am


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.