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?
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.
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.
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.
Using weak_ptr and shared_ptr across threads is safe; the weak_ptr/shared_ptr objects themselves aren't thread-safe.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With