Boost logo

Boost :

From: William Kempf (sirwillard_at_[hidden])
Date: 2000-09-08 14:52:54


--- In boost_at_[hidden], "Bill Wade" <bill.wade_at_s...> wrote:
> > From: William Kempf [mailto:sirwillard_at_m...]
> Using the buffer class from ConditionVariable.html. Suppose I want
to write
> a non-blocking buffer::receive(). I know you're thinking about
adding a
> timeout to wait(), but before I can even call wait() you want me to
have a
> lock.

Firstly, the amount of time you'll block in this case is negligible,
so it's not a good example of what you're trying to do here.
However, I think I get the idea here.
 
> If the mutex is recursive I could use
>
> M::try_lock tlk(mutex);
> if(tlk)
> {
> M::lock lk(mutex);
> wait(lk, ...);
> DoSomethingInteresting();
> }

With out a recursive mutex this is as simple as:

mutex::try_lock tlk(mx);
if (tlk)
{
   cond.wait(tlk, ...);
   DoSomethingInteresting();
}

The second lock is not needed. The condition wait() is templated to
accept any type of mutex lock.
 
> I was wondering if you had a workable solution for the case where
the mutex
> is non-recursive. In other words I'm suggesting that there be a
conversion
> from try_lock to lock (of course the conversion is allowed to fail).

There's not a need to convert from a try_lock to a lock. The only
danger with the current interface is that a bad programmer could code
the following:

mutex::try_lock tlk(mx); // Assume it fails
cond.wait(tlk, ...); // We aren't really locked here!

This seems like a big hole in the safety I've been discussing here.
However, it's a different topic. If you fail to check a try_lock or
timed_lock for success you've entered undefined territory with or
with out the call to wait(). This is why I originally thought that
these types of locks should throw an exception if they failed to
construct (failed to lock), but the consensus was that this was
overkill. For right now I'm going to not take sides on this and will
leave it with a need to check validity after construction.

Bill Kempf


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