Boost logo

Boost :

From: Mattias Flodin (flodin_at_[hidden])
Date: 2002-05-17 00:57:00


Here's another idea: To gain access to lock() and unlock() function
you must first create a "lock guard" object which, upon destruction,
will force the synchronization primitive to be unlocked. This would be
done in a scope surrounding the critical code. For instance, using
your code example:

{
GuardLock g1(m1);
GuardLock g2(m1);
g1.lock();
do_something_to_m1_shared_data();
g2.lock();
do_something_to_m1_and_m2_shared_data();
g1.unlock();
do_something_to_m2_shared_data();
g2.unlock();

// If we forgot to unlock anything, it will be unlocked here
}

Of course, the danger with this is that you may forget to unlock
something and it will be unlocked eventually, but it will be held
longer than necessary, thus reducing parallelism (or potentially
causing a deadlock).

But it seems, on the other hand, that a lock with move semantics would
have the same problems. With auto_ptr the idea is sort of that "we
don't have to care about how long this lives, it will be taken care of
for us." But with locks, knowing the exact lifetime of a lock is
likely to become more important.

/Mattias

On Thu, May 16, 2002 at 11:05:45AM -0500, William E. Kempf wrote:
> One night while trying to fall asleep my mind drifted to this problem (yeah, I know what that says about me), and it dawned on me that the standard already has a solution to a very similar problem. The std::auto_ptr<> template solves a similar issue through "ownership" and "move semantics" instead of the more traditional copy semantics. This allows you to pass a std::auto_ptr<> out of one "scope" and into another, passing the ownership and insuring only one "ptr" will ever delete the object. I could apply the same technique to the ScopedLock concepts and allow the lock "ownership" to be exclusive and transferrable. In many ways this seems like a much better solution then a lock_operations<> template. However, there are issues with "move semantics" that have caused a lot of questions about how to use std::auto_ptr<> correctly, and these issues would exist here as well. Also, I'm not 100% sure this solution will cover all use cases where the ScopedLock is problematic. So what I'm looking for is commen
ts on whether or not this solution is viable and/or the solution I should implement. Thoughts anyone?
>
> Bill Kempf

-- 
Mattias Flodin <flodin_at_[hidden]>  -  http://www.cs.umu.se/~flodin/
Room NADV 102
Department of Computing Science
Umeå University
S-901 87 Umeå, Sweden
--
"There are two ways of constructing a software design; one way is to make it
so simple that there are obviously no deficiencies, and the other way is to
make it so complicated that there are no obvious deficiencies.  The first
method is far more difficult." -- C. A. R. Hoare

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