c++ - Boost Thread 的 boost::unique_lock 是作用域锁吗?

标签 c++ multithreading boost

我了解由 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_lockunique_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/

相关文章:

multithreading - 在 Posix 上旋转的关键部分?

php - 在后台运行异步作业 (laravel)

用于 VS2005 的 C++ std::tr2

c++ - 我还需要多线程还是它已经过时了?

C++ Windows - 如何从其 PID 获取进程路径(错误)

c++ - 传递给 IMediaFilter::Run 的偏移参数

java - 如果花费的时间太长则跳过函数

c++ - G++ 找不到 boost 库

c# - return 0xfe + ceil(x) 返回什么?

c++ - 使用 C++ 和 RAII 读取文件