我了解由 boost::mutex::scoped_lock
锁定的变量在超出范围时会自动解锁。
boost::unique_lock
怎么样,变量超出范围时会自动解锁吗?
任何人也可以指出该功能的引用。
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??? ......
}
谢谢。
最佳答案
scoped_lock
是 unique_lock
。 在 mutex.hpp 中:
typedef unique_lock<mutex> scoped_lock;
如果获得了锁,析构函数调用unlock()
。因此,它会在超出范围时释放。
见 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.
关于c++ - Boost Thread 的 boost::unique_lock 是作用域锁吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9494100/