C++ Meyers Singleton - 线程安全(互斥量的等效代码?) [英] C++ Meyers Singleton - thread safe (code equivalent for mutex?)
问题描述
上周有人向我指出了一段这样的代码:
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;
}
方法 getInstance ,被指出是正确的,原来是 getIntance(StaticMutex),编码不是线程安全的 (c++98) 因为互斥量是在方法中创建的,它是静态的,并且使用静态互斥锁,我遵循静态方法中的静态实例的规则创建一次,不再创建,但此规则自不应用于互斥锁.我有疑问,改正可以吗?每个访问该方法(静态互斥锁)的线程都会创建自己的互斥锁?我读到该操作仅适用于类中的方法,但是因为互斥锁是在静态方法中静态创建的,所以它将被创建一次.我是否正确理解了这个概念?
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?
推荐答案
在 C++11(由 std::mutex 隐含)中,整个 Meyers 单例用两行表示:
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;
}
不需要其他任何东西.问题本身很不清楚,因为您在同一上下文中谈论 C++98 和 std::mutex,而这些并没有加起来.
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.
这篇关于C++ Meyers Singleton - 线程安全(互斥量的等效代码?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!