title: Singleton with multithreads
body: <p>This question was asked in an interview. The first part was to write the singleton class:</p>
  
  <pre><code>class Singleton
  {
      static Singleton *singletonInstance;
      Singleton() {}
  
    public:
      static Singleton* getSingletonInstance()
      {
          if(singletonInstance == null)
          {
              singletonInstance = new Singleton();
          }
          return singletonInstance;
      }
  };
  </code></pre>
  
  <p>Then I was asked how to handle this <code>getSingletonInstance()</code> in a multithreaded situation. I wasn't really sure, but I modified as:</p>
  
  <pre><code>class Singleton 
  {
      static Singleton *singletonInstance;
      Singleton() {}
      static mutex m_;
  
    public:
      static Singleton* getSingletonInstance()
      {
          m_pend();
          if(singletonInstance == null)
          {
              singletonInstance = new Singleton();
          }
          return singletonInstance;
      }
  
      static void releaseSingleton()
      {
          m_post();
      }
  };
  </code></pre>
  
  <p>Then I was told that although a mutex is required, pending and posting a mutex is not efficient as it takes time. And there is a better way to handle to this situation.</p>
  
  <p>Does anybody know a better and more efficient way to handle the singleton class in a multithreaded situation?</p>