This question was asked in an interview. The first part was to write the singleton class:
class Singleton
{
    static Singleton *singletonInstance;
    Singleton() {}
  public:
    static Singleton* getSingletonInstance()
    {
        if(singletonInstance == null)
        {
            singletonInstance = new Singleton();
        }
        return singletonInstance;
    }
};
Then I was asked how to handle this getSingletonInstance() in a multithreaded situation. I wasn't really sure, but I modified as:
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();
    }
};
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.
Does anybody know a better and more efficient way to handle the singleton class in a multithreaded situation?
 
     
     
     
     
    