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
呢?下面的代码中是否存在任何竞态条件?(我的平台是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)
}
f3
中对g_w
的读取将看到值nullptr
或p_s
- 但是该行为不被标准保证。特别地,如果普通单字写入是非原子性的,则实现可能返回一个“撕裂”的值,即部分旧值和部分新值。 - Caseyf3()
和f4()
的可见代码是正确的。然而,注释掉的代码是不正确的:// 1. p_s destroy will modify g_w (write g_w)
。在f4()
中更新g_w
并同时通过g_w.lock()
读取g_w
在f3()
中是未定义的行为! - Kai Petzkef4
中的注释是错误的。p_s
超出作用域不会影响g_w
,它们是不同的对象。只有控制块会被调整。 - LWimsey