Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2005-02-15 17:59:19


Mark Deric wrote:
> On Tue, 15 Feb 2005 03:04:35 +0200
> "Peter Dimov" <pdimov_at_[hidden]> wrote:
>
>> No, because ~Lock will be called twice.
>
> Fair enough. I guess I was willing to overlook the absence of a copy
> ctor in Raz's pseudo-code that "does the right thing".

It's not easy to add a copy constructor that does the right thing, though.
:-) It needs to be a "move constructor" modeled after auto_ptr, or it needs
a reference count.

Of course you can always abuse shared_ptr<Dummy>( &d,
mem_fn(&Dummy::unlock) ) as a Lock class. ;-) More evil ideas at:

http://boost.org/libs/smart_ptr/sp_techniques.html#as_lock
http://boost.org/libs/smart_ptr/sp_techniques.html#wrapper

[...]

> I guess the second paragraph of your initial reply gets at the point;
> is locking to "full-expression" scope useful? I can think of a
> danger:
>
> cout << x->a << long_running_overloaded_insertion_rhs;
>
> From my read, the lock wouldn't be given up until after the second <<
> gets evaluated. Does this make sense; or am I missing something else?

Consider also:

cout << x->a << x->a;

which (a) will be a problem if the mutex is not recursive and (b) locks
twice.

(a) can be avoided:

cout << x->a;
cout << x->a;

but now the two lines may actually output different values, if x->a is
modified by another thread.

The idiom may have its uses, but the more traditional approach of locking at
logical blocks instead of every access is more efficient, doesn't require
recursive locks, and within the logical block the state of the object will
be consistent.


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