关于weak_ptr的线程安全

新手上路,请多包涵
std::shared_ptr<int> g_s = std::make_shared<int>(1);
void f1()
{
    std::shared_ptr<int>l_s1 = g_s; // read g_s
}

void f2()
{
    std::shared_ptr<int> l_s2 = std::make_shared<int>(3);
    std::thread th(f1);
    th.detach();
    g_s = l_s2; // write g_s
}

关于上面的代码,我知道不同的线程读写相同的 shared_ptr 会导致竞争条件。但是 weak_ptr 怎么样?下面的代码中是否有任何竞争条件? (我的平台是微软VS2013。)

 std::weak_ptr<int> g_w;

void f3()
{
    std::shared_ptr<int>l_s3 = g_w.lock(); //2. here will read g_w
    if (l_s3)
    {
        ;/.....
    }
}

void f4()
{
    std::shared_ptr<int> p_s = std::make_shared<int>(1);
    g_w = p_s;

    std::thread th(f3);
    th.detach();
    // 1. p_s destory will motify g_w (write g_w)
}

原文由 Leonhart Squall 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 993
1 个回答

我知道我迟到了,但是在搜索“weak_ptr thread”时会出现这种情况,而凯西的回答并不是全部。 shared_ptrweak_ptr 都可以在线程中使用而无需进一步同步。

对于 shared_ptr ,有很多文档(例如在 cppreference.comstackoverflow 上)。您可以安全地访问 shared_ptr 从不同线程指向同一个对象。您只是不能从两个线程中敲击同一个指针。换句话说:

 // Using p and p_copy from two threads is fine.
// Using p from two threads or p and p_ref from two threads is illegal.
std::shared_ptr<A> p = std::make_shared<A>();
std::shared_ptr<A> &p_ref = p;
std::shared_ptr<A> p_copy = p;

要在您的代码中解决该问题,请将 g_s 作为参数(按值)\* 传递给 f1()

对于弱指针,安全保证隐藏在 weak_ptr::lock 的文档中:

有效地返回 expired() ? shared_ptr<T>() : shared_ptr<T>(*this) ,原子执行。

您可以使用 weak_ptr::lock() shared_ptr 而无需进一步同步。 这在 Boost 和 Chris Jester-Young 的 这个 SO 回答 中也得到了证实。

同样,您必须确保不要从一个线程修改相同的 weak_ptr 同时从另一个线程访问它,因此也将 g_w f3() 通过值传递给 --- 。

原文由 Christian Aichinger 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题