相关疑难解决方法(0)

关于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
}
Run Code Online (Sandbox Code Playgroud)

关于上面的代码,我知道不同的线程读取和写入相同的shared_ptr导致竞争条件.但是怎么样weak_ptr?下面的代码中是否有竞争条件?(我的平台是Microsoft 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)
}
Run Code Online (Sandbox Code Playgroud)

c++ multithreading weak-ptr c++11

15
推荐指数
3
解决办法
7941
查看次数

标签 统计

c++ ×1

c++11 ×1

multithreading ×1

weak-ptr ×1