Meyers 实现的单例模式线程安全吗?

Is Meyers#39; implementation of the Singleton pattern thread safe?(Meyers 实现的单例模式线程安全吗?)
本文介绍了Meyers 实现的单例模式线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:

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

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

GCC 和 VS 支持该功能 (并发动态初始化和销毁​​,也称为 MSDN 上的魔术静态) 如下:

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
  • 起支持

感谢@Mankarse 和@olen_gam 的评论.

Thanks to @Mankarse and @olen_gam for their comments.

在 C++03 中,此代码不是线程安全的.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 实现的单例模式线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)