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


- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- C++ 协变模板 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01