如果要锁定实例上的方法,则必须Mutex
为每个实例和方法创建一个:
class Foo
def initialize
@blue_mutex = Mutex.new
@red_mutex = Mutex.new
end
def blue
@blue || @blue_mutex.synchronize do
@blue ||= Blue.new
end
end
def red_mutex
@red || @red_mutex.synchronize do
@red ||= Red.new
end
end
end
接受参数是否存在逻辑错误Thread.exclusive
?
class Foo
def blue
@blue || Thread.exclusive("#{object_id}/blue") do
@blue ||= Blue.new
end
end
def red
@red || Thread.exclusive("#{object_id}/red") do
@red ||= Red.new
end
end
end
Thread.exclusive
如果可以只接受一个定义排他性范围的参数,为什么要创建互斥锁?