Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 758
Johannes Avatar asked Apr 09 '15 14:04

Johannes


People also ask

Is shared_ptr thread safe?

A std::shared_ptr consists of a control block and its resource. Yes, the control block is thread-safe; but no, the access to the resource is not thread-safe. That means, modifying the reference counter is an atomic operation and you have the guarantee that the resource will be deleted exactly once.

What happens when shared_ptr goes out of scope?

The smart pointer has an internal counter which is decreased each time that a std::shared_ptr , pointing to the same resource, goes out of scope – this technique is called reference counting. When the last shared pointer is destroyed, the counter goes to zero, and the memory is deallocated.

Is Make_shared thread safe?

The snippet you pulled from msdn basically means "access to the control block is thread-safe" so other shared_ptr<> instances can be created and destroyed on different threads as much as necessary. //In thread 1 local_instance = make_shared<myClass>(); This is fine.

Is Weak_ptr thread safe?

Using weak_ptr and shared_ptr across threads is safe; the weak_ptr/shared_ptr objects themselves aren't thread-safe.


1 Answers

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.

like image 145
Mike Seymour Avatar answered Oct 05 '22 06:10

Mike Seymour