关于weak_ptr的竞争条件 [英] about race condition of weak_ptr

查看:129
本文介绍了关于weak_ptr的竞争条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1。
i发布了几天前的问题(关于weak_ptr的threadafe ),我现在有另一个相关的问题。
如果我做这样的事情,会在上面的例子中引入一个竞争条件g_w(我的平台是ms vs2013)

1. i posted the question(About threadsafe of weak_ptr) several days ago,and I have the other related question now. If i do something like this,will introduce a race condition as g_w in above example ?(my platform is ms 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() //f4 run in main thread
{
    std::shared_ptr<int> p_s = std::make_shared<int>(1);
    g_w = p_s;

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

2.我知道std :: shared_ptr / weak_ptr派生自std :: tr1 :: shared_ptr / weak_ptr,std :: tr1 :: shared_ptr / weak_ptr派生于boost :: shared_ptr / weak_ptr,实施有任何差异

2.As i know std::shared_ptr/weak_ptr derived from std::tr1::shared_ptr/weak_ptr, and std::tr1::shared_ptr/weak_ptr derived from boost::shared_ptr/weak_ptr, are there any difference on the implement,especially, in the relief of thread-safe.

推荐答案

完成的 std ::线程与正在创建的线程中的指定函数的调用同步,即 f4 之前发生的 everything 在开始执行 f3 时,新线程保证可以看到 std :: thread th 的构造。特别是对 g_w f4 g_w = p_s;

The completed construction of a std::thread synchronizes with the invocation of the specified function in the thread being created, i.e., everything that happens in f4 before the construction of std::thread th is guaranteed to be visible to the new thread when it starts executing f3. In particular the write to g_w in f4 (g_w = p_s;) will be visible to the new thread in f4.

您的注释中的语句 // 1. p_s destory会使g_w(写g_w)不正确。销毁 p_s 不以任何方式访问 g_w 。在大多数实现中,它修改了一个公共控制块,用于跟踪对引号的所有共享和弱引用。对标准库实现内部对象的任何修改是库的问题,使线程安全,而不是你的,根据C ++ 11§17.6.5.9/7实现可以在线程之间共享自己的内部对象,如果对象不可见

The statement in your comment // 1. p_s destory will motify g_w (write g_w) is incorrect. Destruction of p_s does not access g_w in any way. In most implementations it does modify a common control block that's used to track all shared and weak references to the pointee. Any such modifications to objects internal to the standard library implementation are the library's problem to make threadsafe, not yours, per C++11 § 17.6.5.9/7 "Implementations may share their own internal objects between threads if the objects are not visible to users and are protected against data races."

假设程序中没有对 g_w 进行并发修改,没有其他线程执行 f3 ,这个程序在 g_w 上没有数据竞争。

Assuming no concurrent modifications to g_w somewhere else in the program, and no other threads executing f3, there is no data race in this program on g_w.

这篇关于关于weak_ptr的竞争条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆