boost::unique_lock 与 boost::lock_guard

boost::unique_lock vs boost::lock_guard(boost::unique_lock 与 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_locklock_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

基础教程推荐