问题
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:
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.
来源:https://stackoverflow.com/questions/34001420/c-meyers-singleton-thread-safe-code-equivalent-for-mutex