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 to perform write/reads on instance variables of a class or metaclass object?
What are the differences between these three (contrived) examples in terms of thread safety?
EXAMPLE 1: MUTUAL EXCLUSION
class BestUser # (singleton class)
@@instance_lock = Mutex.new
# Memoize instance
def self.instance
@@instance_lock.synchronize do
@@instance ||= best
end
end
end
EXAMPLE 2: INSTANCE VARIABLE STORAGE
class BestUser # (singleton class)
# Memoize instance
def self.instance
@instance ||= best
end
end
EXAMPLE 3: INSTANCE VARIABLE STORAGE ON METACLASS
class BestUser # (singleton class)
# Memoize instance
class << self
def instance
@instance ||= best
end
end
end
See Question&Answers more detail:os