Re: Fwd: memory



On 5/18/06, Chris Vine <chris cvine freeserve co uk> wrote:
On Tuesday 16 May 2006 11:16, Ramashish Baranwal wrote:
> boost::shared_ptr is thread safe.

"Thread safe" can mean many different things.  boost::shared_ptr<> is thread
safe in the sense in which a bare pointer is thread safe.

Thats right. boost::shared_ptr<> is not designed to provide mutual
exclusion. Its thread safe in the sense of maintaining its own
integrity, i.e. you can safely use shared_ptr(s) in multiple threads
to access the same underlying object. Its upto the underlying object
to provide mutual exclusion (preventing simulataneous modification).


But you cannot safely modify a shared pointer (ie apply a
non-const operation to the shared pointer) in one thread and read from or
modify the same instance of shared pointer in another thread.

shared_ptr is used to provide access to the underlying object, so you
need not modify the "same instance of the shared_ptr" in another
thread. Normally different threads used different instances of
shared_ptrs all providing access to the same object. As a side note if
you look closely even assignment of shared_ptrs modify their internals
(reference count). But that is an implementation detail.

you cannot safely modify the referenced object in one thread and read or
modify it in another thread, unless the object does its own locking.)

What this means is that you can have the same object referenced by a container
of shared pointers in one thread and a container of shared pointers in
another thread provided that you arrange separate locking of the referenced
object.  The circumstances in which you might want to do that are quite
limited.


Not really. This cirumstance is in fact very common for single
threaded applications, for applications which use their resources in
only one thread, or for applications which serialize the modification
of their resources to one thread. I see shared_ptr as a way of
providing automatic memory management and not mutual exclusion. The
cost of having locking for the underlying object in a shared_ptr would
be prohibitive for applications that doesn't require it.

Ram



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]