Search code examples
c++multithreadingshared-ptrswap

Is shared_ptr swap thread safe?


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?


Solution

  • 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.