Meyers对Singleton模式的实现是线程安全的吗?[英] Is Meyers implementation of Singleton pattern thread safe?

本文是小编为大家收集整理的关于Meyers对Singleton模式的实现是线程安全的吗?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

以下使用延迟初始化的 Singleton (Meyers Singleton) 线程实现是否安全?

static Singleton& instance()
{
     static Singleton s;
     return s;
}

如果不是,为什么以及如何使其线程安全?

推荐答案

C++11,它是线程安全的.根据标准,§6.7 [stmt.dcl] p4:

<块引用>

如果控制进入在变量初始化的同时声明,并发执行应该等待初始化完成.

GCC 和 VS 对该功能的支持 (具有并发性的动态初始化和销毁​​,也称为 MSDN 上的 Magic Statics) 如下:

感谢@Mankarse 和@olen_gam 的评论.


C++03 中,此代码不是线程安全的.Meyers 有一篇名为 "C++ 和双重检查锁定的风险" 的文章,其中讨论了该模式的线程安全实现,结论或多或少是,(在 C++03 中)围绕实例化方法的完全锁定基本上是确保所有平台上正确并发的最简单方法,而大多数形式的双检查的锁定模式变体可能会受到某些架构上的竞争条件的影响,除非指令与策略性地放置内存屏障交错.

本文地址:https://www.itbaoku.cn/post/627461.html

问题描述

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?

推荐答案

In C++11, it is thread safe. According to the standard, §6.7 [stmt.dcl] p4:

If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.

GCC and VS support for the feature (Dynamic Initialization and Destruction with Concurrency, also known as Magic Statics on MSDN) is as follows:

Thanks to @Mankarse and @olen_gam for their comments.


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.