boost::unique_lock vs boost::lock_guard(boost::unique_lock 与 boost::lock_guard)
问题描述
我不太明白这两个锁类之间的区别.在 boost 文档中说,boost::unique_lock 不会自动实现锁定.
I don't well understand the difference betweeen these two lock classes.
In boost documentation it is said, boost::unique_lock doesn't realize lock automatically.
这是否意味着 unique_lock 和 lock_guard 之间的主要区别在于使用 unique_lock 我们必须显式调用 lock() 函数?
Does it mean that the main difference between unique_lock and lock_guard is that with unique_lock we must call explicitly the lock() function ?
推荐答案
先回答你的问题.不,您不需要在 unique_lock 上调用锁.见下图:
First to answer your question. No you don't need to call lock on a unique_lock. See below:
unique_lock 只是一个具有更多功能的锁类.在大多数情况下,lock_guard 可以满足您的要求并且足够了.
unique_lock 为您提供了更多功能.例如,如果您需要超时或者如果您想将锁定推迟到对象构造之后的时间点,则进行定时等待.所以这在很大程度上取决于你想做什么.顺便说一句:下面的代码片段做同样的事情.
The unique_lock is only a lock class with more features. In most cases the lock_guard will do what you want and will be sufficient.
The unique_lock has more features to offer to you. E.g a timed wait if you need a timeout or if you want to defer your lock to a later point than the construction of the object. So it highly depends on what you want to do.
BTW: The following code snippets do the same thing.
boost::mutex mutex;
boost::lock_guard<boost::mutex> lock(mutex);
boost::mutex mutex;
boost::unique_lock<boost::mutex> lock(mutex);
第一个可以用来同步访问数据,但是如果你想使用条件变量,你需要去第二个.
The first one can be used to synchronize access to data, but if you want to use condition variables you need to go for the second one.
这篇关于boost::unique_lock 与 boost::lock_guard的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:boost::unique_lock 与 boost::lock_guard
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
