Dan Tao
Dan Tao

Reputation: 128317

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?

Upvotes: 7

Views: 200

Answers (2)

djconnel
djconnel

Reputation: 431

x += 1

is equivalent in every way to

x = x + 1

(if you re-define +, you also automatically redefine the result of +=)

In this notation, it's clearer this is not an atomic operation, and is therefore not guaranteed thread-safe.

Upvotes: 0

Linuxios
Linuxios

Reputation: 35783

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.

Upvotes: 2

Related Questions