Boost logo

Boost :

From: Anthony Williams (anthony_w.geo_at_[hidden])
Date: 2007-11-01 06:33:51


Yuval Ronen <ronen_yuval_at_[hidden]> writes:

> Howard Hinnant wrote:
>> On Oct 30, 2007, at 3:43 PM, Yuval Ronen wrote:
>>
>>>>> 2. Make sizeof(unique_lock) smaller - no need for bool owns.
>>>> Even if we remove defer_lock, unique_lock will still need the
>>>> internal bool to support try and timed locks. This functionality
>>>> still retains a reference to the mutex even if the try/timed lock
>>>> fails (so that further action with the mutex can be easily taken).
>>> This is something I don't understand. Why should the lock retain a
>>> reference to the mutex even if the try/timed lock fails?
>>
>> Because if the try_lock fails, I might want to take some corrective
>> action and then do a blocking lock() on the mutex. If the lock has
>> retained the reference to the mutex, I don't have to store that
>> reference elsewhere "just in case" the try_lock fails.
>
> But now you do it (by "it" I mean "retained the reference, just in
> case") all the time, for everyone, even if unnecessary. I believe this
> is a rare use case (I never written or read such code), and it's also
> something that can be easily implemented externally (either as a
> unique_lock wrapper, or not). It seems pity that everyone should pay
> that cost.

unique_lock needs to retain a reference to the mutex in order to unlock it in
the destructor. The cost comes from the fact that retaining the reference
means you need a separate bool to indicate locked/unlocked. Depending on the
pointer format and alignment requirements of the mutex, this could be stored
as the LSB of a pointer to the mutex to save the space (for example).

unique_lock is a lock object associated with a mutex. The mutex doesn't change
through the life of the lock object, though it may be locked or unlocked many
times. Code that uses the lock object doesn't need to know which mutex it
refers to: it can just call lock() and unlock() on the lock object. Condition
variables have to do that: they call unlock() at the start of the wait, and
lock() when done.

lock_guard is a simple always-owns-the-lock object, and thus saves the space
of the boolean.

Anthony

-- 
Anthony Williams
Just Software Solutions Ltd - http://www.justsoftwaresolutions.co.uk
Registered in England, Company Number 5478976.
Registered Office: 15 Carrallack Mews, St Just, Cornwall, TR19 7UL

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