Sash Sash - 12 days ago 7
Ruby Question

Multithreading + Ruby arrays

I find it hard to understand if it is safe to insert to array in Ruby with multiple threads.

As far as I understand Ruby arrays, just like any other objects are not thread safe. But does it mean that insertion to array is also not safe?

For instance, I have the following code:

arr=[]
threads = []

for i in 1..5
threads << Thread.new do
for j in 1..1000
arr << ((1000 * i) + j)
end
end
end

threads.each(&:join)

puts arr.length


It just spins 5 threads that each pushes 1000 numbers to an array. It seems that the result is always consistent and I always get result of 5000 elements in the array.

So is it safe to do it like that?

Answer

As far as I understand Ruby arrays, just like any other objects are not thread safe. But does it mean that insertion to array is also not safe?

Right. Array insertions are not safe on Ruby, but if you run your code in MRI, it's going to work every time because GIL. GIL (global interpreter lock) was made to prevent this kind of issues, but JRuby and Rubinius does not have GIL and works as you expect (some times produce 5000, some times less).

This is because with GIL only one thread is active at time and because that, there is no problem adding you elements to the array.

Read this.