gpt4 book ai didi

c++ - 共享指针的双重检查锁定

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:00:45 25 4
gpt4 key购买 nike

免责声明:我有 Java 背景,因此,我不知道 C++(和相关库)的许多内部机制是如何工作的。

我已经阅读了足够多的资料,知道双重检查锁定是邪恶的,正确和安全地实现单例模式需要适当的工具。

我认为以下代码可能不安全,受编译器重新排序和未初始化对象分配的影响,但我不确定我是否遗漏了一些我不了解该语言的内容。

typedef boost::shared_ptr<A> APtr;

APtr g_a;
boost::mutex g_a_mutex;
const APtr& A::instance()
{
if (!g_a)
{
boost::mutex::scoped_lock lock(g_a_mutex);
if (!g_a)
{
g_a = boost::make_shared<A>();
}
}

return g_a;
}

我相信实际代码是在 C++03 下编译的。

这个实现不安全吗?如果是,怎么办?

最佳答案

是的,双重检查锁定模式在古老的语言中是不安全的。我不能比 What's wrong with this fix for double checked locking? 中的解释做得更好:

The problem apparently is the line assigning instance -- the compiler is free to allocate the object and then assign the pointer to it, OR to set the pointer to where it will be allocated, then allocate it.

如果您使用的是 C++11 std::shared_ptr,则可以使用 atomic_load and atomic_store在共享指针对象上,它们保证彼此正确组合并与互斥体组合;但如果您使用的是 C++11,您也可以只使用动态初始化的 static 变量,它保证是线程安全的。

关于c++ - 共享指针的双重检查锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36063617/

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