Boost logo

Boost :

Subject: Re: [boost] [thread] unlock on multiple lockables
From: Anthony Williams (anthony.ajw_at_[hidden])
Date: 2009-11-23 07:02:35

Gottlob Frege <gottlobfrege_at_[hidden]> writes:

> On Sun, Nov 22, 2009 at 9:08 PM, Vicente Botet Escriba
> <vicente.botet_at_[hidden]> wrote:
>> Hi,
>> I don't know if I have already requested that but ...
>> Is there any deep reason to don't provide the equivalent of the free
>> functions lock, try_lock
> My guesses at the reasons:
>> Non-member function lock(Lockable1,Lockable2,...)
>> Non-member function lock(begin,end)
> Locking a bunch of locks is a recipe for deadlock. Do we lock them in
> order? Then hold lock1, lock2, waiting to get lock3? Sounds
> dangerous.

That's why these functions (which are part of the current boost release)
don't lock in order, they use a try-and-back-off algorithm to avoid

>> Non-member function try_lock(Lockable1,Lockable2,...)
>> Non-member function try_lock(begin,end)
> Sounds even scarier - after trying lock1, do you try lock2? - so you
> don't get lock1, you do get lock2, other thread gets the opposite ==
> deadlock.

Again, there is no risk of deadlock here. If a thread fails to acquire
one of the locks it releases all the locks it has acquired so far.

>> to unlock multiple lockables?
>> Non-member function unlock(Lockable1,Lockable2,...)
>> Non-member function unlock(begin,end)

> Only other reason would be because they are not common enough, and
> easy enough to write on your own (using for_each, etc) for when you do
> need them.

Precisely. You can just call unlock on each item in turn. There are no
complications here: you must own the locks to be able to call unlock,
and the order doesn't matter.

> Oh, and lastly, because in general direct calls to lock/unlock are
> discouraged (although at times useful/necessary) and scope_lock is
> preferred.

Sort of. If your locks are scoped to the current block with
unique_lock or lock_guard then you don't need to use a block-unlock
function, even if you used lock() to acquire them all (having
constructed the unique_lock instances with defer_lock).


Author of C++ Concurrency in Action |
just::thread C++0x thread library   |
Just Software Solutions Ltd         |
15 Carrallack Mews, St Just, Cornwall, TR19 7UL, UK. Company No. 5478976

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