Here is my test code
class bar
{
public:
explicit bar(int x) : num(x) {}
int get_num()
{
return num;
}
private:
int num;
};
shared_ptr<bar> ptr_store;
void get_func()
{
while (1)
printf("get_num:%d\n", ptr_store->get_num());
};
void set_func()
{
while (1)
//ptr_store = make_shared<bar>(1);
atomic_exchange(&ptr_store, make_shared<bar>(1));
}
int main()
{
ptr_store = make_shared<bar>(-1);
std::thread t1(get_func);
std::thread t2(set_func);
t1.join();
t2.join();
}
I wonder why this program wouldn't make a core dump?
If set_func
in t2
destroy the origin ptr_store
when t1
is using ptr_store->get_num()
, it could cause some fault? Is it Guaranteed by shared_ptr
? Or it just a coincidence.
Test environment:
OS: Ubuntu 20.04 LTS
Clang: clang version 3.9.1
G++: gcc version 7.5.0
update: I think there is no possibility that two threads access one object. atomic_exchange
or reset
can be considered an atomic operation. When setting the new object, the old object will not be changed.
Aucun commentaire:
Enregistrer un commentaire