Skip to content

Instantly share code, notes, and snippets.

@manumilou
Created March 19, 2019 22:29
Show Gist options
  • Save manumilou/cd916c1a21a3c257904fd8180e1ee74d to your computer and use it in GitHub Desktop.
Save manumilou/cd916c1a21a3c257904fd8180e1ee74d to your computer and use it in GitHub Desktop.
Appending to arrays is not thread-safe in Ruby.
array = []
5.times.map do
Thread.new do
1000.times do
array << nil
end
end
end.each(&:join)
puts array.size
@manumilou
Copy link
Author

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