c++ - Meyers 实现的 Singleton 模式线程安全吗?

标签 c++ multithreading design-patterns

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

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

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

最佳答案

C++11 ,它是线程安全的。根据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 对该功能的支持( Dynamic Initialization and Destruction with Concurrency ,也称为 Magic Statics on MSDN )如下:

感谢@Mankarse 和@olen_gam 的评论。


C++03 ,这段代码不是线程安全的。 Meyers 有一篇文章叫做 "C++ and the Perils of Double-Checked Locking"其中讨论了该模式的线程安全实现,结论或多或少是(在 C++03 中)围绕实例化方法的完全锁定基本上是确保所有平台上正确并发的最简单方法,而大多数形式的 double -checked 锁定模式变体可能会受到 race conditions on certain architectures 的影响, 除非指令与策略性位置的内存屏障交错。

关于c++ - Meyers 实现的 Singleton 模式线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1661529/

相关文章:

c++ - Codeblocks 找不到英特尔 C++ 编译器 (Linux Mint)

ruby - 介绍性 Ruby 线程问题

design-patterns - 如何在 uml 图中注释设计模式

java - 如果您已经知道树结构怎么办?复合模式有替代方案吗?

c++ - C++代码执行过程中如何连接dll文件?

c++ - 如何授予函数模板好友访问类的权限?

multithreading - Hadoop的Mapper对象是跨线程共享的吗?

c# - C# 中的有效存储库 - 将方法放在哪里?

c++ - 了解 std::regex 声明:运行时的 regex_error 异常

java - 为什么这个简短的片段不适合多线程应用程序?