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
基础教程推荐
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- c++ STL设置差异 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
