1. i posted the question(About thread-safety of weak_ptr) several days ago,and I have the other related question now. If i do something like this,will introduce a race condition as g_w in above example ?(my platform is 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.As i know std::shared_ptr/weak_ptr derived from std::tr1::shared_ptr/weak_ptr, and std::tr1::shared_ptr/weak_ptr derived from boost::shared_ptr/weak_ptr, are there any difference on the implement,especially, in the relief of thread-safe.
The completed construction of a
std::thread
synchronizes with the invocation of the specified function in the thread being created, i.e., everything that happens inf4
before the construction ofstd::thread th
is guaranteed to be visible to the new thread when it starts executingf3
. In particular the write tog_w
inf4
(g_w = p_s;
) will be visible to the new thread inf4
.The statement in your comment
// 1. p_s destory will motify g_w (write g_w)
is incorrect. Destruction ofp_s
does not accessg_w
in any way. In most implementations it does modify a common control block that's used to track all shared and weak references to the pointee. Any such modifications to objects internal to the standard library implementation are the library's problem to make threadsafe, not yours, per C++11 § 17.6.5.9/7 "Implementations may share their own internal objects between threads if the objects are not visible to users and are protected against data races."Assuming no concurrent modifications to
g_w
somewhere else in the program, and no other threads executingf3
, there is no data race in this program ong_w
.