-1

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.

Community
  • 1
  • 1
Leonhart Squall
  • 810
  • 1
  • 7
  • 15

2 Answers2

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.

Casey
  • 41,449
  • 7
  • 95
  • 125
0

@Casey

Firstly, I complete my code.

int main()
{
  f4();
  getchar();
  retrun 0;
}

And I find some code in my visual studio 2013. Is there a race?

Leonhart Squall
  • 810
  • 1
  • 7
  • 15
  • If you look at the `weak_ptr` assignment operator, you should see that `weak_ptr`s hold a reference to the control block by incrementing `_Weaks`. The shared object may be deallocated when the last `shared_ptr` is destroyed, but the control block with the reference counts will live until the last *weak* pointer is destroyed. – Casey Dec 25 '13 at 05:15
  • Realy,thank you for your help.I just noticed _Uses,but not _Weaks.So in the other question(http://stackoverflow.com/questions/20705304/about-threadsafe-of-weak-ptr)I only call f4() in main there is no race,is that right? – Leonhart Squall Dec 25 '13 at 06:01