Boost logo

Boost :

From: Howard Hinnant (hinnant_at_[hidden])
Date: 2004-08-09 18:08:05

On Aug 9, 2004, at 3:20 PM, Bronek Kozicki wrote:

> Howard Hinnant wrote:
>> I can't think of any reason for concern about unlock order.
> <blush> Ehm, I mixed other things with multithreaded programming

<chuckle> I've been thinking that maybe you're right! :-)

Though I haven't thought it all the way through yet. Maybe by the time
I write this, it will come together...

I've been thinking about:

template <class TryLock1, class TryLock2>
class transfer_lock

where transfer_lock hold references to two other locks. The lock()
function transfers ownership from lock2 to lock1, and the unlock()
function transfers ownership from lock1 to lock2. Might be useful for
transferring ownership from an upgradable_lock to a scoped_lock, and
then back again, within a scope.

So far so good.

Ok, but what if you do the opposite:

typedef scoped_lock<rw_mutex> WriteLock;
typedef upgradable_lock<rw_mutex> ReadLock;

WriteLock write_lock(m);
if (...)
     ReadLock read_lock(m, defer_lock);
     transfer_lock<ReadLock, WriteLock> lock(read_lock, write_lock);
     // here m is downgraded from write to read
     // m is upgraded from read to write before exiting scope
// here m is write locked, whether or not if-branch was taken

I.e. in this (possibly perverse) example, "lock" doesn't block and
"unlock" does. And if you start combining transfer_lock<L1, L2> with a
lock_both<L1, L2>, I'll bet you could come up with an example where
both "lock" and "unlock" block. And you might get shot for even
suggesting such evilness! :-)

But at any rate, when "unlock" can block, the rules are turned on their
head. And if you start tossing a lock like that into a generic lock-2
algorithm, things start looking very evil. Maybe the best advice is
just: don't do that! I.e. a precondition of using a generic lock-2
algorithm (or lock_both<L1,L2>) would be that the unlock() on each of
the locks must be non-blocking. Still pondering this one (no, it
didn't come together) ...


Boost list run by bdawes at, gregod at, cpdaniel at, john at