在Ruby中对类变量执行写入/读取不是线程安全的.对实例变量执行写入/读取似乎是线程安全的.也就是说,对类或元类对象的实例变量执行写/读是否是线程安全的?
在线程安全方面,这三个(人为的)示例之间有什么区别?
例1: 相互排斥
class BestUser # (singleton class)
@@instance_lock = Mutex.new
# Memoize instance
def self.instance
@@instance_lock.synchronize do
@@instance ||= best
end
end
end
Run Code Online (Sandbox Code Playgroud)
例2: 实例变量存储
class BestUser # (singleton class)
# Memoize instance
def self.instance
@instance ||= best
end
end
Run Code Online (Sandbox Code Playgroud)
例3: 在METACLASS上安装可变存储器
class BestUser # (singleton class)
# Memoize instance
class << self
def instance
@instance ||= best
end
end
end
Run Code Online (Sandbox Code Playgroud) ruby multithreading metaprogramming thread-safety ruby-1.9.2