是Meyers实现的Singleton模式线程安全吗? [英] Is Meyers implementation of Singleton pattern thread safe?
问题描述
下面的实现,使用延迟初始化的Singleton(Meyers Singleton)线程安全吗?
Is the following implementation, using lazy initialization, of Singleton (Meyers Singleton) thread safe?
static Singleton& instance()
{
static Singleton s;
return s;
}
如果没有,为什么以及如何使它线程安全?
If not, why and how to make it thread safe?
推荐答案
在 C ++ 11 ,它是线程安全的。根据标准,§ 6.7 [stmt.dcl] p4
:
In C++11, it is thread safe. According to the standard, §6.7 [stmt.dcl] p4
:
如果控制输入
正在初始化,并发执行将等待完成初始化。
GCC和VS支持该功能(具有并发性的动态初始化和销毁,也称为作为 MSSQL上的Magic Statics )如下:
GCC and VS support for the feature (Dynamic Initialization and Destruction with Concurrency, also known as Magic Statics on MSDN) is as follows:
- Visual Studio:自后支持Visual Studio 2015
- GCC:自 GCC 4.3 < a>
感谢@Mankarse和@olen_gam的意见。
Thanks to @Mankarse and @olen_gam for their comments.
在 C ++ 03 中,此代码wasn' t线程安全。有一篇Meyers的文章称为C ++和双重检查锁定的危险,其中讨论了线程安全实现模式和结论,或多或少(在C + + 03)围绕实例化方法的完全锁定基本上是确保所有平台上的正确并发的最简单的方法,而大多数形式的双检查锁定模式变体可能遭遇某些架构上的竞争条件,除非指令与策略性地交错放置内存屏障。
In C++03, this code wasn't thread safe. There is an article by Meyers called "C++ and the Perils of Double-Checked Locking" which discusses thread safe implementations of the pattern, and the conclusion is, more or less, that (in C++03) full locking around the instantiating method is basically the simplest way to ensure proper concurrency on all platforms, while most forms of double-checked locking pattern variants may suffer from race conditions on certain architectures, unless instructions are interleaved with strategically places memory barriers.
这篇关于是Meyers实现的Singleton模式线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!