Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Boost Thread's boost::unique_lock a scoped lock?

I understand that variable locked by a boost::mutex::scoped_lock is automatically unlocked when it is out of scope.

How about boost::unique_lock, does it automatically unlock the variable when it is out of scope?

Can anyone also point a reference for that feature as well.

double x;
boost::mutex x_mutex;

void foo() 
{
    {
         boost::unique_lock<boost::mutex> lock(x_mutex);
         x = rand();
    }    
    ...... some calculation which takes 10 second ......
    ...... is x still locked here??? ......    
}

Thanks.

like image 986
2607 Avatar asked Feb 29 '12 05:02

2607


1 Answers

scoped_lock is a unique_lock. In mutex.hpp:

typedef unique_lock<mutex> scoped_lock;

The destructor calls unlock() if the lock was acquired. So, it will release when it goes out of scope.

See http://www.boost.org/doc/libs/1_49_0/doc/html/thread/synchronization.html

not only does it provide for RAII-style locking, it also allows for deferring acquiring the lock until the lock() member function is called explicitly, or trying to acquire the lock in a non-blocking fashion, or with a timeout. Consequently, unlock() is only called in the destructor if the lock object has locked the Lockable object, or otherwise adopted a lock on the Lockable object.

like image 103
jspcal Avatar answered Nov 07 '22 12:11

jspcal