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
}
Regarding the code above, I know different threads reading and writing the same shared_ptr
leads to race conditions. But how about weak_ptr
? Is there any race condition in the code below? (My platform is 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)
}
shared_ptr
andweak_ptr
fall under the same blanket threadsafety requirements as all other standard library types: simultaneous calls to member functions must be threadsafe if those member functions are non-modifying (const
) (Detailed in C++11 §17.6.5.9 Data Race Avoidance [res.data.races]). Assignment operators are notably notconst
.