vendredi 20 mai 2022

Question about the thread-safety of using shared_ptr

As it's well known that shared_ptr only guarantees access to underlying control block is thread safe and no guarantee made for accesses to owned object.

Then why there is a race condition in the code snippet below:

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
}

In the code snippet above, the owned object of the shared pointer named g_s are not accessed indeed.

I am really confused now. Could somebody shed some light on this matter?

Aucun commentaire:

Enregistrer un commentaire