Singleton & Multi-threading

后端 未结 6 626
有刺的猬
有刺的猬 2021-01-05 17:36

I have the following class

class Singleton
{
  private:

    static Singleton *p_inst;
    Singleton();

  public:

    static Singleton * instance()
             


        
6条回答
  •  自闭症患者
    2021-01-05 18:18

    I will be brief: it depends on your compiler.

    • If your compiler implements multi-threading synchronization for local static (ie static instances embedded in a method), then use it and be done with it.
    • If not, Herb Sutter proved it was impossible.

    Now, you have to realize that you may not need this.

    There are 2 ways to deal with this, that do not require any multithread awareness.

    1. Simply use a static instance instead of dynamically allocate it. Safe and simple. May cause issue with initialization order if you need to access it from another static variable
    2. Create the singleton instance BEFORE having more than one thread. The usual trick is to call it from main.

    Of course, the real question is: can't you just pass a reference to the object rather than creating a global variable ? It would make testing easier ;)

提交回复
热议问题