Search code examples
c++multithreadingsynchronizationsmart-pointers

Is std::shared_ptr assignment atomic?


In the context of C++ shared pointers, imagine two threads, t1 and t2, both engaged in assigning values to a shared pointer (s1). If t1 assigns the value 2, and in close succession, t2 endeavors to assign the value 1, will t2 wait for the entirety of t1's assignment, encompassing the memory allocation phase, or will it proceed without waiting?

std::shared_ptr<int> s1;

std::thread t1([=s1]() { while (true) s1 = std::make_shared<int>(2); });
std::thread t2([=s1]() { while (true) s1 = std::make_shared<int>(1); });
// ...

Solution

  • std::shared_ptr not atomic itself. You can use std::atomic<std::shared_ptr> which is partial specialisation for std::atomic.