C++ Meyers Singleton - thread safe (code equivalen

2019-09-09 02:38发布

I was pointed last week about a piece of code like this:

#include <pthread.h>
namespace NSTest
{
class SingletonClass
{
public:


    static SingletonClass & getInstance()
    {
        static  pthread_mutex_t mutex;
        pthread_mutex_lock(&mutex);
        if(singletonPtr==nullptr)
        {
            createInstence();
        }
        return (*singletonPtr);
        pthread_mutex_unlock(&mutex);

    }

private:
    static void createInstence()
    {
        static SingletonClass static_SingletonClass;
        singletonPtr=&static_SingletonClass;

    }
    static SingletonClass * singletonPtr;

};

SingletonClass * SingletonClass::singletonPtr=nullptr;


class SingletonClassNoStatic
{
public:
    static SingletonClassNoStatic & getInstance()
    {
        pthread_mutex_lock(&mutex);
        if(singletonPtr==nullptr)
        {
            createInstence();
        }
        return (*singletonPtr);
        pthread_mutex_unlock(&mutex);
    }
private:
    static void createInstence()
    {
        static SingletonClassNoStatic static_SingletonClass;
        singletonPtr=&static_SingletonClass;

    }
    static SingletonClassNoStatic * singletonPtr;

    static  pthread_mutex_t mutex;
};
SingletonClassNoStatic * SingletonClassNoStatic::singletonPtr=nullptr;
pthread_mutex_t SingletonClassNoStatic::mutex;
}
int main()
{

    NSTest::SingletonClass::getInstance();
    NSTest::SingletonClassNoStatic::getInstance();

    return 0;
}

The method getInstance , was pointed to be the correct one, and the original was getIntance(StaticMutex), that coded is not thread safe (c++98) because the mutex is created in the method , that it was static and with a static mutex, I was following the rule of the static instance in static method is created once and no longer is created, but this rule since not to be applied to the mutex. I have doubts, it that correction be ok? Each thread that accesses that method (static mutex) will create its own mutex? I was reading that that action is only to method that are method from class, but because the mutex is created static in a static method it will be created once. Am I correctly understanding the concept?

1条回答
该账号已被封号
2楼-- · 2019-09-09 03:13

In C++11 (which is implied by std::mutex) the whole Meyers singleton is expressed in two lines:

Singleton& instance() {
  static Singleton instance;

  return instance;
}

Nothing else is needed. The question itself is very unclear, since you talk about C++98 and std::mutex in the same context, and those do not add up.

The other problem with posted code is that it is not a Meyer's singleton to begin with.

查看更多
登录 后发表回答