Boost logo

Boost Users :

Subject: Re: [Boost-users] Is weak_ptr lock method thread safe?
From: Gottlob Frege (gottlobfrege_at_[hidden])
Date: 2013-04-24 12:30:13


On Mon, Apr 22, 2013 at 4:26 AM, Andrea Galeazzi <galeazzi_at_[hidden]> 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 threadweak_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



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net