Search code examples
rubymultithreadingglobal-variables

Ruby: How do I share a global variable amongst threads that are running an object.method


I am running a ruby script that creates several threads.

I want to make the threads have access to a common variable that lets the main thread know when to join the threads.

I am trying to do this with a $global variable, but the threads don't seem the be able to access the $global.

class IO_ 
  def change(number)
    sleep(60 * number)
    $trade_executed = true
  end
end 

io = IO_.new 
numbers = 1, 2
$threads = {}
$trade_executed = false

def start_threads(numbers)
  numbers.each do |number|
    $threads[number] = Thread.new {io.change(number)}
  end
end

start_threads(numbers)

while true
  p $trade_executed
  p $threads
  sleep(10)
end

The above $trade_executed will always be 'false'.

But if I move the method change outside of the io object it works.


Solution

  • The problem is in the function start_threads. You called io.change(number) in that function, but the local variable io is not defined in that function. The consequence is that both threads died due to NameError.

    You can change the start_threads function as this:

    def start_threads(numbers, io)
      numbers.each do |number|
        $threads[number] = Thread.new {io.change(number)}
      end
    end
    

    and call it like this:

    start_threads(numbers, io)