Why there is no race condition in the code snippet below,
#include<memory>
#include<thread>
std::shared_ptr<int> g_s = std::make_shared<int>(1);
void f1(std::shared_ptr<int> sp)
{
std::shared_ptr<int>l_s1 = sp; // read g_s
}
void f2()
{
std::shared_ptr<int> l_s2 = std::make_shared<int>(3);
std::thread th(f1, g_s);
th.detach();
g_s = l_s2; // write g_s
}
int main()
{
std::thread(f2).join();
}
whereas there is a race condition in the code snippet below?
#include<memory>
#include<thread>
std::shared_ptr<int> g_s = std::make_shared<int>(1);
void f1(std::shared_ptr<int>& sp)
{
std::shared_ptr<int>l_s1 = sp; // read g_s
}
void f2()
{
std::shared_ptr<int> l_s2 = std::make_shared<int>(3);
std::thread th(f1, std::ref(g_s));
th.detach();
g_s = l_s2; // write g_s
}
int main()
{
std::thread(f2).join();
}
My current thought about this question is seen at the first answer. But I am not so sure yet. Could somebody please shed some light this matter?