rubyconcurrencyatomicmri

Is assignment an atomic operation in ruby MRI?


Let's say I have these two methods in my class.

def set_val(val)
  @val = val
end

def get_val
  @val
end

I'll spawn multiple threads to call set_val with different values. Is it guaranteed that reading from @val returns the correct value, i.e., not the last assigned value, but a value that was passed to set_val? Could I get something strange when reading? Is the assignment operation atomic? Is it indivisible irrespective of the number of threads?


Solution

  • This depends a bit on the Ruby implementation you are using. As for MRI Ruby (the "default" Ruby), this is a safe (atomic) operation due to its Global Interpreter Lock which guards some operations such as assignments from bein interrupted by context switches.

    JRuby also guarantees that some operations are thread-safe, including assignment to instance variables.

    In any case, please make sure to take into account that any such concurrent access can be serialized in a seemingly random way. That is, you can't guarantee which threads assigns first and which one last unless you use explicit locks such as a Mutex.