假设我的 Rails 项目中有一个 Ruby 类,它正在设置一个实例变量。
class Something
def self.objects
@objects ||= begin
# some logic that builds an array, which is ultimately stored in @objects
end
end
end
是否可以@objects
多次设置?是否有可能在一个请求期间,在执行上述begin
/之间的代码时end
,可以在第二个请求期间调用此方法?我想这真的归结为 Rails 服务器实例是如何分叉的问题。
我应该改为使用Mutex
或线程同步吗?例如:
class Something
def self.objects
return @objects if @objects
Thread.exclusive do
@objects ||= begin
# some logic that builds an array, which is ultimately stored in @objects
end
end
end
end