0

I was reading the difference between a lock_guard and a unique_lock and I found out that a unique_lock is an enhanced version of a lock_guard. Such that with a unique lock a lock can always be deferred.I was reading this article and I came across the boost::lock. I wanted to know how I can use this method. I tried the following :

boost::mutex mutx;
boost::unique_lock<boost::mutex> guard (mutx,boost::defer_lock);
boost::lock(guard); //too few arguments in function call.

I would appreciate it if someone could explain to me what boost::lock does and how it works.Thanks

Rajeshwar
  • 11,179
  • 26
  • 86
  • 158

2 Answers2

0

Did you mean

mutex mutx
unique_lock<mutex> guard(mutx,defer_lock);
guard.lock();

?

Once you have a lock_guard or unique_lock, you stop messing with the mutex directly, and you work on the guard object.

DanielKO
  • 4,422
  • 19
  • 29
  • Thanks just fixed my code. I understand that part. However I wanted to know what `boost::lock` does and how to use it – Rajeshwar Oct 31 '13 at 02:28
  • Did you try [reading the docs](http://www.boost.org/doc/libs/1_54_0/doc/html/thread/synchronization.html#thread.synchronization.lock_functions)? I says there, it locks multiple objects avoiding deadlocks. Doesn't make much sense to call it with a single argument, although it could provide more uniformity; heck, it could even support zero argument and do nothing... but that's not how it was designed. – DanielKO Oct 31 '13 at 02:31
0

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
    }
}
user12
  • 128
  • 2
  • 6