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++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01