提高:: unique_lock VS的boost :: lock_guard [英] boost::unique_lock vs boost::lock_guard

查看:148
本文介绍了提高:: unique_lock VS的boost :: lock_guard的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不很明白betweeen这两个锁类的区别。
在提升文档据说,的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之间的主要区别我们必须显式调用的锁()功能?

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有更多的功能,以提供给你。例如一个定时的等待,如果你需要超时或者如果你想你的锁推迟到比对象的构造稍后。因此,它在很大程度上取决于你想要做什么。
BTW:以下code片段做同样的事情。

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.

这篇关于提高:: unique_lock VS的boost :: lock_guard的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆