Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Ruby threads not collide on a write?

From past work in C# and Java, I am accustomed to a statement such as this not being thread-safe:

x += y;

However, I have not been able to observe any collision among threads when running the above code in parallel with Ruby.

I have read that Ruby automatically prevents multiple threads from writing to the same data concurrently. Is this true? Is the += operator therefore thread-safe in Ruby?

like image 521
Dan Tao Avatar asked Jun 27 '12 23:06

Dan Tao


1 Answers

Well, it depends on your implementation and a lot of things. In MRI, there is a such thing as the GVL (Giant VM Lock) which controls which thread is actually executing code at a time. You see, in MRI, only one thread can execute Ruby code at a time. So while the C librarys underneath can let another thread run while they use CPU in C code to multiply giant numbers, the code itself can't execute at the same time. That means, a statement such as the assignment might not run at the same time as another one of the assignments (though the additions may run in parallel). The other thing that could be happening is this: I think I heard that assignments to ints are atomic on Linux, so if you're on Linux, that might be something too.

like image 155
Linuxios Avatar answered Sep 29 '22 21:09

Linuxios