简体   繁体   English

易失的Singleton成员?

[英]Volatile Singleton member?

I have a state engine that uses a Singleton software design pattern. 我有一个使用Singleton软件设计模式的状态引擎。 The state engine can be accessed by multiple threads. 状态引擎可以由多个线程访问。 The object is initialized from the main thread at program start up and is not designed for Lazy initialization. 该对象是在程序启动时从主线程初始化的,不适用于延迟初始化。

My question is, should I make the public static members volatile like this: 我的问题是,是否应该像这样使公共静态成员易变:

class CStateEngine final
{
    private:
        /* Contains the Singleton object */
        static CStateEngine* instance;
    protected:
        CStateEngine();
    public:
        static CStateEngine* Instance() volatile;   // Returns the Singleton instance
        static void DeleteInstance() volatile;  // Deletes the Singleton instance
}

The volatile keyword in C++ is NOT the same as in any other languages. C ++中的volatile关键字与其他任何语言都不相同。 In C++ it means that the compiler will make sure that the value is always newly read from memory, and never a cached value is used. 在C ++中,这意味着编译器将确保始终从内存中新读取该值,并且永远不要使用缓存的值。

It has it's uses the embedded world and other places. 它具有使用嵌入式世界和其他地方的功能。 If you wanted to have an always up to date view of a certain variable you'd mark it as volatile . 如果您想拥有某个变量的最新视图,可以将其标记为volatile

It has nothing however to do with multithreading. 但是,它与多线程无关。

You should not use a singleton in a multi-threaded environment, because it will be a cause for contention as multiple threads try to access your object. 您不应在多线程环境中使用单例,因为当多个线程尝试访问您的对象时,这将导致争用。 It will cause your programs to lag and it entirely defeats using threads in the first place. 它将导致您的程序滞后,并且首先使用线程将其完全失败。

You should pass objects around, and you should be able to create new ones as you need them. 您应该传递对象,并且应该能够根据需要创建新对象。

If you can't do that, review your design. 如果您不能这样做,请检查您的设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM