gpt4 book ai didi

ruby - 单例类会在多线程应用程序中产生问题吗?

转载 作者:数据小太阳 更新时间:2023-10-29 06:51:59 24 4
gpt4 key购买 nike

这可能是过早的优化,或过早的过度谨慎,但我避免在一些类上使用单例,因为我担心在未来我需要以多线程方式运行我的应用程序,而且单例会造成冲突和困惑。单例在 Ruby 中是否有这个问题,或者是否有某种内置的命名空间,以便当一个类引用单例时,只返回同一线程上的单例?

编辑:澄清这些是可观察的类,当更新时会导致其他正在观察它们的类更新。我不确定这是否是线程安全的,但我知道现在我正在大量传递这些可观察的类,这有点烦人。而且它们看起来确实像是自然的单例类。

最佳答案

这是一个使单线程安全的例子。您必须像对待任何其他具有状态 (@things) 并且不是不可变(只读)的对象一样对待它。 getter 和 setter 需要通过 Mutex(互斥)访问内部状态。

require 'singleton'

class MyObject
include Singleton

def initialize
@things = []
@mutex = Mutex.new
end

def add(thing)
with_mutex { @things << thing }
end

def things
with_mutex { @things }
end

def clear
with_mutex { @things.clear }
end

def self.add(thing)
instance.add(thing)
end

def self.things
instance.things
end

def self.clear
instance.clear
end

private

def with_mutex
@mutex.synchronize { yield }
end
end

进一步阅读:http://rubylearning.com/satishtalim/ruby_threads.html

关于ruby - 单例类会在多线程应用程序中产生问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6943691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com