Search code examples
c++multithreadingatomicshared-ptr

how to use atomic_store set shared_ptr to nullptr in multithread


in std::shared_ptr thread safety, code like this is not thread safe:

//In thread 1
shared_ptr<myClass> private = global;
...

//In thread 2
global = make_shared<myClass>();

and use atomic_store and atomic_load is thread safe


//In thread 1
shared_ptr<myClass> private = atomic_load(&global);
...

//In thread 2
atomic_store(&global, make_shared<myClass>());
...

I try to use atomic_store set ptr to nullptr, but it is not allowed like this:

std::atomic_store(&global, nullptr);

I want to know why can not set shared_ptr to null safely


Solution

  • I find I can use shared_ptr() instead nullptr, like this

    shared_ptr<myClass> private = global;
    std::atomic_store(&global, shared_ptr<myClass>());