-1

1.我几天前发布了这个问题(关于weak_ptr的线程安全),我现在有另一个相关的问题。如果我做这样的事情,会在上面的例子中引入一个竞争条件作为 g_w 吗?(我的平台是 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::tr1::shared_ptr/weak_ptr派生的std::shared_ptr/weak_ptr和从boost::shared_ptr/weak_ptr派生的std::tr1::shared_ptr/weak_ptr,在实现上有什么区别吗?特别是在线程安全方面。

4

2 回答 2

1

a 的完成构造std::thread与正在创建的线程中指定函数的调用同步,即,在构造 of 之前发生的所有事情都保证在新线程开始执行时对它是可见的。特别是对in ( ) 的写入将对 in 中的新线程可见。f4std::thread thf3g_wf4g_w = p_s;f4

您评论中的陈述// 1. p_s destory will motify g_w (write g_w)不正确。销毁p_sg_w以任何方式访问。在大多数实现中,它确实修改了一个公共控制块,该控制块用于跟踪对指针对象的所有共享和弱引用。根据 C++11 § 17.6.5.9/7,对标准库实现内部对象的任何此类修改都是库的问题,以使线程安全,而不是您的问题用户并受到保护免受数据竞争。”

g_w假设程序中的其他地方没有并发修改,并且没有其他线程正在执行f3,则该程序中没有数据竞争g_w

于 2013-12-24T23:54:14.663 回答
0

@凯西

首先,我完成我的代码。

int main()
{
  f4();
  getchar();
  retrun 0;
}

我在我的 Visual Studio 2013 中找到了一些代码。 有比赛吗?

于 2013-12-25T04:40:47.547 回答