2

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?

sawa
  • 165,429
  • 45
  • 277
  • 381

1 Answers1

3

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.

Holger Just
  • 52,918
  • 14
  • 115
  • 123
  • 1
    Could you provide the source of your answer for MRI? – Antonio González Borrego Mar 06 '19 at 19:23
  • Well, the whole idea of a GIL is to guarantee that individual operations on a Ruby level will never be interrupted by a concurrent thread. Even things like the += operator (which is definitely unsafe to use on JRuby and others) is [safe](https://github.com/jondot/pcwr/blob/dca092d03d060ece104e3aa7c1aef9efe2cd224e/README.md#state-of-the-union) on MRI. – Holger Just Mar 06 '19 at 20:43