17

Here are some code snippets.

std::shared_ptr<int> global(new int(1)); 


void swapper(int x)
{
    std::shared_ptr<int> sp(new int(x));  
    global.swap(sp); 
}

Suppose i wanted to call swapper in parallel threads. Would that be threadsafe?

I am aware of this answer. It shows how assigning the pointer is not thread safe if i reassign a value to global.

My question is if the swap member function is in itself thread safe.

On the one hand the control block functions of shared_ptr are thread safe. On the other hand i assume that i am swithing the pointers to the control blocks, so it should not be thread safe.

What is the connection there? Is swap thread safe?

Community
  • 1
  • 1
Johannes
  • 6,490
  • 10
  • 59
  • 108

1 Answers1

23

No, swap isn't thread safe, but there's another function that is:

atomic_store(&global, sp);

There's also atomic_exchange which returns the old value, if you need that.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • [`atomic_exchange`](http://en.cppreference.com/w/cpp/atomic/atomic_exchange)? But we're dealing with a `shared_ptr`. – Barry Apr 09 '15 at 14:42
  • 5
    @Barry: No, [`atomic_exchange`](http://en.cppreference.com/w/cpp/memory/shared_ptr/atomic). – Mike Seymour Apr 09 '15 at 14:44
  • That makes way more sense then! – Barry Apr 09 '15 at 14:50
  • [K13](https://stackoverflow.com/users/13327906) posted an [Answer](https://stackoverflow.com/a/67077247) saying "Be aware that atomic_axchange is deprecated for std::shared_ptr since C++20: [http://open-std.org/JTC1/SC22/WG21/docs/papers/2020/p2139r0.html#3.18](http://open-std.org/JTC1/SC22/WG21/docs/papers/2020/p2139r0.html#3.18)" – Scratte Apr 19 '21 at 08:20