Search code examples
ruby-on-railsrubymultithreadingmutual-exclusion

Mutual Exclusion not happened in Ruby


Program:

def inc(n)
    n + 1
end

sum = 0
threads = (1..10).map do
    Thread.new do
        10_000.times do
            sum = inc(sum)
        end
    end
end
threads.each(&:join)
p sum

Output:

$ ruby MutualExclusion.rb 
100000
$ 

My expected output of above program is less than 100,000. Because, the above program create 10 threads and each of the thread update the shared variable 'sum' to 10,000 times. But during execution of the program, mutual exclusion will definitely happen. Because, mutual exclusion is not handled here. So I expect less than 100,000 as output. But it gives exactly 100,000 as output. How it is happened ? Who handle the mutual exclusion here ? And how I experiment this problem(ME).


Solution

  • The default interpreter for Ruby (MRI) doesn't execute threads in parallel. The mechanism that's preventing your race condition from introducing casually unexpected behavior is the Global Interpreter Lock (GIL).

    You can learn more about this, including a very similar demonstration, here: http://www.jstorimer.com/blogs/workingwithcode/8085491-nobody-understands-the-gil