问题
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.
回答1:
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 in f4
before the construction of std::thread th
is guaranteed to be visible to the new thread when it starts executing f3
. In particular the write to g_w
in f4
(g_w = p_s;
) will be visible to the new thread in f4
.
The statement in your comment // 1. p_s destory will motify g_w (write g_w)
is incorrect. Destruction of p_s
does not access g_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 executing f3
, there is no data race in this program on g_w
.
回答2:
@Casey
Firstly, I complete my code.
int main()
{
f4();
getchar();
retrun 0;
}
And I find some code in my visual studio 2013.
来源:https://stackoverflow.com/questions/20754370/about-race-condition-of-weak-ptr