Boost logo

Boost Users :

Subject: Re: [Boost-users] Is weak_ptr lock method thread safe?
From: Klaim - Joël Lamotte (mjklaim_at_[hidden])
Date: 2013-04-23 12:25:40


On Mon, Apr 22, 2013 at 10:26 AM, Andrea Galeazzi <galeazzi_at_[hidden]> wrote:

> In other words, is lock method atomic in respect to deference of the
> shared point?

Yes it is thread-safe, that's the whole point of the system:
shared_ptr is implemented (in boost or std implementations) with an atomic
counter used to sync the moment when the object need to be destroyed.
Once the object is destroyed, all wp.lock() calls will return null
shared_ptr. Just lock the shared_ptr from any thread (by copy) and check if
it's null or not,
or use wp.expired() if you don't want to aquire the object but just check
if it's still alive.

It is also good to know that there is some kind of synchronization on
shared_ptr copy/construction that might
in some cases, not be wanted for single-threaded applications where the
cost isn't acceptable.

Joel Lamotte



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