简体   繁体   中英

Volatile Singleton member?

I have a state engine that uses a Singleton software design pattern. 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. 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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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