Singleton & Multi-threading

后端 未结 6 634
有刺的猬
有刺的猬 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

    You should ask yourself what you mean by thread safety.

    • Does your singleton actually need thread safety?

      If not, consider a thread-static approach

    • Do you want to guarantee that no two instances of the singleton ever get created?

      If not, your above solution is probably fine, without any locking: you've got a race condition on construction - but you don't care since eventually only one will survive - however, you may have a resource leak unless you're careful, which may or may not be significant. (This is essentially a cache).

    • Do you want to guarantee that eventually only one instance remains?

    • Do you care about locking costs?

      If not (which is quite common), you can just put a lock around it and be happy.

    A singleton is a pattern that can address various problems - but what flavor of thread-safety is required has little to do with the singleton pattern itself and everything to do with what you want it for.

提交回复
热议问题