The code below is seen at this SO.
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)
}
Although, the same object of weak_ptr
(i.e. g_w
) is read and written by two different threads, updating g_w
in f4()
is before the constructation of thread object (i.e. std::thread th(f3);
) in which reading g_w
via g_w.lock()
is invoked. The two operations could not be run at the same time. So I think the code snippet is correct and no data race would occur.
I have read the comments of the said SO again and again but I really can’t understand, say.
Updating g_w in f4() and at the same time reading g_w via g_w.lock() in f3() is undefined behaviour!