On Mon, Apr 22, 2013 at 4:26 AM, Andrea Galeazzi <galeazzi@korg.it> wrote:
I googled this question but, although there are many discussions about it, I didn't find a clear answer.
Can I assume the following piece of code to be thread safe?

shared_ptr<T> p1(new XXX); //Main thread
weak_ptr<T> wp(sp); //Main thread

//Then I run two threads: A and B
p1.reset(); // thread A
shared_ptr<T> p2 = wp.lock(); // thread B
In other words, is lock method atomic in respect to deference of the shared point?



Yes it is thread safe.

To be clear (because I've seen this confusion before):

shared_ptr<T> p1(new XXX);

p1.reset(); // thread A
p1.reset(); // thread B

is NOT thread safe - used the same shared_ptr in 2 threads

shared_ptr<T> p1(new XXX);
shared_ptr<T> p2(p1);

p1.reset(); // thread A
p2.reset(); // thread B

is thread safe - 2 shared_ptrs referencing the same object.


Same with weak_ptr and various combinations.

What you are doing is thread-safe.  It is part of the docs, can be seen in the implementation (although it is hard to see), and tons of code would break if it wasn't.

Tony