线程安全的单例在C ++ 11 [英] Thread-safe singleton in C++11
问题描述
我知道以下是在C ++ 11中实现单例的线程安全方法:
I know the following is a thread-safe way to implement a singleton in C++11:
Foo* getInst()
{
static Foo* inst = new Foo(...);
return inst;
}
我读过这个回答下面也是线程安全的:
I read in this answer that the following is also thread-safe:
Foo& getInst()
{
static Foo inst(...);
return inst;
}
它是真线程安全的吗?
Isn'那么一个问题是Foo 的实例将被分配在单个堆栈帧中不会被分配在堆上?
Is it really thread-safe?
Isn't it a problem that the instance of Foo will be allocated in a single stack frame will not be allocated on the heap?
如果是
推荐答案
静态变量是
Both版本使用内部编译器保护(即 __ cxa_guard_acquire()
和 __ cxa_guard_release()
,其功能等同于 mutex :: lock()
和 mutex :: unlock()
),以确保序列化访问特殊变量,
Both versions use internal compiler guards (namely __cxa_guard_acquire()
and __cxa_guard_release()
, which are functionally equivalent to mutex::lock()
and mutex::unlock()
) to ensure serialized access to a special variable that tells whether or not your global instances are already initialized or not.
您的代码:
Foo& getInst()
{
static Foo inst(...);
return inst;
}
在编译之后实际上会是这样:
will actually look like that after the compilation:
Foo& getInst()
{
static Foo inst; // uninitialized - zero
static guard instGuard; // zero
if (is_initialized(instGuard) == false)
{
__cxa_guard_acquire(instGuard);
// do the initialization here - calls Foo constructor
set_initialized(instGuard);
__cxa_guard_release(instGuard);
}
return inst;
}
所以你的两个exampes都是线程安全的。
So both of your exampes are thread safe.
这篇关于线程安全的单例在C ++ 11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!