可以将unique_lock与recursive_mutex一起使用吗? [英] Can unique_lock be used with a recursive_mutex?

查看:478
本文介绍了可以将unique_lock与recursive_mutex一起使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据unique_lock可用于通过以下方式进行递归锁定:声明std::unique_lock<std::recursive_mutex>,实际上可以编译.

According the this, unique_lock can be used for recursive locking by declaring a std::unique_lock<std::recursive_mutex>, and in fact that compiles fine.

但是,从检查代码(gcc 4.8.2和4.9.0)可以看出,unique_lock并不服从_Mutex.lock,而是实现了lock方法本身:

However, it appears from examining the code (gcc 4.8.2 and 4.9.0) that unique_lock doesn't defer to _Mutex.lock, but rather implements the lock method itself:

  void
  lock()
  {
if (!_M_device)
  __throw_system_error(int(errc::operation_not_permitted));
else if (_M_owns)
  __throw_system_error(int(errc::resource_deadlock_would_occur));
else
  {
    _M_device->lock();
    _M_owns = true;
  }

很明显,这可以防止互斥锁的递归锁定,实际上,尝试递归锁定会引发resource_deadlock_would_occur异常.

Clearly, this prevents recursive locking of the mutex, and in fact attempting to recursively lock throws the resource_deadlock_would_occur exception.

我在这里遗漏了什么吗,这是一个错误,还是unique_lock的文档错了?

Am I missing something here, is this a bug, or is the documentation for unique_lock just wrong?

TIA !!!

推荐答案

一个常见的错误是将mutexlock混淆. mutex是可以在线程之间共享的对象(否则它将没有用).但是,锁本身不是线程安全的对象.不应在线程之间共享它.它通常是堆栈上的本地对象.例如:

A common mistake is to confuse the mutex with the lock. A mutex is an object that can be shared among threads (otherwise it would be useless). A lock however is not itself a thread-safe object. It should not be shared among threads. It is typically a local object on a stack. For example:

void foo()
{
     std::unique_lock<std::mutex> lk(mut);  // mut comes from some other scope
     // mut locked here
     // ...
}    // mut unlocked here

在上面的示例中,如果递归调用foo(),则您将具有未定义的行为,因为您将递归锁定mut.在每次递归中,您都会得到一个新的unique_lock.因此unique_lock不知道递归.如果确实需要递归调用foo(),则需要使用递归互斥锁,例如:

In the example above, if foo() is called recursively, you have undefined behavior because you will lock mut recursively. On each recursion, you get a new unique_lock though. So the unique_lock is not aware of the recursion. If you really need to call foo() recursively, you need to use a recursive mutex, for example:

void foo()
{
     std::unique_lock<std::recursive_mutex> lk(mut);  // mut comes from some other scope
     // mut locked here
     // ...
}    // mut unlocked here

所以:是的,您可以使用std::unique_lock<std::recursive_mutex>,是的,您的实现是正确的.

So: Yes, you can use std::unique_lock<std::recursive_mutex>, and yes, your implementation is correct.

这篇关于可以将unique_lock与recursive_mutex一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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