Search code examples
ruby-on-railsrubymutex

Ruby Threads Concurrency Issue using Mutex


require 'thread'

mutex = Mutex.new


shared_resource = 0

  for i in 0..10000
    Thread.new do
      mutex.synchronize { shared_resource += 1 }
    end
    Thread.new do
      mutex.synchronize { shared_resource -= 1 }
    end
  end

puts shared_resource

I am trying to run this Ruby program to test mutex.synchronize and get 0 on every run but everytime I run this program It gives me random value. Need help with solving this to get 0 and help me understand how to use Mutex and lock in Ruby


Solution

  • Your issue is not the mutex, since synchronize will lock it during block execution. Your issue is that the thread execution has not completed when you reach puts shared_resource.

    To solve this you need to ensure that all the threads have completed by calling Thread#join for example:

    require 'thread'
    
    mutex = Mutex.new
    
    shared_resource = 0
    threads = []
    
    400.times do |i|
      threads << Thread.new do
        mutex.synchronize {shared_resource += 1}
      end
      threads << Thread.new do
        mutex.synchronize {shared_resource -= 1}
      end
    end
    
    puts shared_resource
    #=> some number
    
    # see how many threads are still running 
    puts threads.map(&:status)
    
    threads.map(&:join)
    
    puts shared_resource
    #=> 0