Performing writes/reads on class variables in Ruby is not thread safe. Performing writes/reads on instance variables appears to be thread safe. That said, is it thread safe
Examples 2 and 3 are exactly the same. They are not thread-safety at all.
Please see the example Below.
class Foo
def self.bar
@bar ||= create_no
end
def self.create_no
no = rand(10000)
sleep 1
no
end
end
10.times.map do
Thread.new do
puts "bar is #{Foo.bar}"
end
end.each(&:join)
It's result is not same. The result is same when using mutex as below.
class Foo
@mutex = Mutex.new
def self.bar
@mutex.synchronize {
@bar ||= create_no
}
end
def self.create_no
no = rand(10000)
sleep 1
no
end
end
10.times.map do
Thread.new do
puts "bar is #{Foo.bar}"
end
end.each(&:join)
It is run on CRuby 2.3.0.