Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2003-02-05 15:40:15


Trey Jackson wrote:
> All,
>
> (Note: I'm not critiquing the design choices, just trying to
> understand the choices and the behavior of the implementation)
>
> I read in the docs that simultaneous reads are ok, but simultaneous
> read/write or write/write are not. Ok, seems like a valid set up.
>
> When I looked at the implementation, it looks like the reference
> counter uses a mutex when BOOST_HAS_THREADS is defined.
>
> Does that mean that if I have thread capability on my boost
> installation (which I do), I pay for the mutex regardless of whether I
> am actually using threads?

In a word, yes. The actual mutex being used depends on the platform. The
overhead is usually acceptable, even with a plain pthread_mutex.

> Secondly, if I'm paying for the cost of a mutex for the reference
> count, why couldn't the shared_ptr also be protected by a mutex?
>
> Thereby making the simultaneous read/write safe (safe in that no
> memory would be leaked b/c the pointers written/read).

Consider this:

// thread A

p->f();

// thread B

p.reset();

--
p->f(); is equivalent to p.operator->()->f(). To make the above work,
operator-> would need to return a proxy that keeps the mutex locked. Even
so, thread B may get there first.
Even if you do
if(p) p->f();
it is still possible for thread A to evaluate if(p) and thread B to
intervene with a reset.
And of course had this been
(*p).f();
thread B can intervene between *p and the actuall call to f(), since there
is no way to insert a locking proxy in operator*.
In short, there is no way for shared_ptr to reliably synchronize your code
for you. It is only responsible for synchronizing its own code.
> Which brings me to a third question.
> Let's say I've got a class (e.g. shared_count) that I sometimes want
> to be protected by a mutex, and sometimes not.  Say, for instance, I
> want it to be protected by default, but sometimes I want to avoid that
> overhead b/c I know I'll be using it in an environment that's already
> protected by a mutex (and can avoid the extra mutex overhead).
Can you demonstrate this with an example?
> Question: is the following design a reasonable one?
> It appears to work for me.
>
> template<class LockingStrategy>
> class mySuperLockedClass : public LockingStrategy
[...]
Looks OK to me.
> Just wondering if the above strategy could be used in the case of
> shared_count, and if not, why not?
Because of the extra LockingStrategy parameter. :-)

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk