Question

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

Was it helpful?

Solution

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
    }
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top