简体   繁体   English

Boost Thread的boost :: unique_lock是一个范围锁吗?

[英]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. 我知道当boost::mutex::scoped_lock超出范围时,由boost::mutex::scoped_lock锁定的变量会自动解锁。

How about boost::unique_lock , does it automatically unlock the variable when it is out of scope? boost::unique_lock怎么boost::unique_lock ,当变量超出范围时会自动解锁变量吗?

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. 谢谢。

scoped_lock is a unique_lock . scoped_lockunique_lock In mutex.hpp: 在mutex.hpp中:

typedef unique_lock<mutex> scoped_lock;

The destructor calls unlock() if the lock was acquired. 如果获取了锁,析构函数会调用unlock() 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 请参阅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. 它不仅提供RAII样式的锁定,还允许延迟获取锁定,直到显式调用lock()成员函数,或者尝试以非阻塞方式或超时获取锁定。 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. 因此,只有在锁定对象锁定了Lockable对象或以其他方式对Lockable对象采用锁定时,才会在析构函数中调用unlock()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM