Created
March 19, 2019 22:29
-
-
Save manumilou/cd916c1a21a3c257904fd8180e1ee74d to your computer and use it in GitHub Desktop.
Appending to arrays is not thread-safe in Ruby.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
array = [] | |
5.times.map do | |
Thread.new do | |
1000.times do | |
array << nil | |
end | |
end | |
end.each(&:join) | |
puts array.size |
Making this code atomic to ensure that it can't be interrupted until it's finished. The simplest way to make an operation like this atomic is to use a lock.
array = []
mutex = Mutex.new
5.times.map do
Thread.new do
mutex.synchronize do
1000.times do
array << nil
end
end
end
end.each(&:join)
puts array.size
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
MRI implementation works as expected because of the GIL (internal mutex).