gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:43:03 24 4
gpt4 key购买 nike

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/53165255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com