The purpose of boost::lock
is to lock several locks ensuring that no deadlock occurs.
Consider the case:
unique_lock<...> a, b;
// thread 1
a.lock();
b.lock();
...
// thread 2
b.lock();
a.lock();
Now if first thread locks the a
lock and then second thread locks the b
lock, you have a problem: both locks are locked and the threads won't execute anything unless one of them unlocks the lock, which is not possible. This condition is called a deadlock.
boost::lock
avoids this problem by unlocking all locks it already locked when it encounters a locked lock. The implementation for the two lock case could look something like this:
template<class L1, class L2>
void lock(L1& l1, L2& l2)
{
while (1) {
if (l1.try_lock()) {
if (l2.try_lock()) {
return;
} else {
l1.unlock();
}
}
// yield (execute another thread) here
}
}