Can Ruby Streams Not Collide When Writing?

From past work in C # and Java, I got used to the statement, for example, this is not thread safe:

x += y; 

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

I read that Ruby automatically prevents multiple threads from writing to the same data at the same time . It's true? Is the += operator thread safe in Ruby?

+7
source share
2 answers

Well, it depends on your implementation and many things. In MRI, there is such a thing as GVL (Giant VM Lock) that controls which thread actually executes the code at a time. You see that in MRI only one thread can execute Ruby code at a time. Therefore, while the C libraries below may allow another thread to work while they use the CPU in the C code to multiply giant numbers, the code itself cannot be executed at the same time. This means that an operator, such as an assignment, may not be launched simultaneously with another one of the assignments (although additions may be performed in parallel). Another thing that can happen is this: I think I heard that int assignments are atomic on Linux, so if you are working on Linux, it could be something too.

+2
source
 x += 1 

equivalent in every way

 x = x + 1 

(if you override + , you also automatically override the result += )

In these notations, this is clearer, this is not an atomic operation, and therefore, thread safety is not guaranteed.

0
source

All Articles