Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::shared_ptr is it safe to use it in multiple threads?

I was trying to find the answer for some time but I failed.

Lets assume that we have a shared_ptr created from one thread. Then we pass this shared_ptr to another 2 threads (using some queue for example). So from this moment there are 2 copies of the original shared_ptr, pointing to the same raw pointer. Both owner threads will take their copies of this shared_ptr from the queue. Then they will pass it to another thread or will destroy it.

Question is - is it safe? Will the raw pointer destroyed correctly (there will be no race to reference counter?) enter image description here

like image 593
user1332475 Avatar asked Jul 15 '12 12:07

user1332475


2 Answers

The C++ standard has almost no guarantees regarding thread safety. The reference count of std::shared_ptr is the only exception: it’s guaranteed to behave as an atomically accessed variable. I believe this is codified in this phrase in §20.7.2.2/4:

Changes in use_count() do not reflect modifications that can introduce data races.

boost::shared_ptr offers the same guarantees:

shared_ptr objects offer the same level of thread safety as built-in types. A shared_ptr instance can be "read" … simultaneously by multiple threads. Different shared_ptr instances can be "written to"… simultaneosly by multiple threads (even when these instances are copies, and share the same reference count underneath.)

like image 67
Konrad Rudolph Avatar answered Sep 24 '22 11:09

Konrad Rudolph


The boost docs state:

Different shared_ptr instances can be "written to" (accessed using mutable operations such as operator= or reset) simultaneosly by multiple threads (even when these instances are copies, and share the same reference count underneath.)

(emphasis mine)

So the crux here is whether you copy the boost::shared_ptrs between threads or not. If you create copies (the "safe" way to use shared_ptrs) you don't have any worries about thread-safety. If however you pass the shared_ptr by reference or pointer, and hence are using the actual same shared_ptr in different threads, you would have to worry about thread-safety, as described in the docs.

like image 30
Fraser Avatar answered Sep 26 '22 11:09

Fraser