【问题标题】:How to avoid locking using lock_guard?如何避免使用 lock_guard 锁定?
【发布时间】:2019-01-04 06:16:12
【问题描述】:

https://en.cppreference.com/w/cpp/thread/lock_guard

(构造函数)
构造一个lock_guard,可选择锁定给定的互斥体

如果锁定是可选的,那么避免锁定的方法是什么?

【问题讨论】:

  • 您是否尝试单击(constructor) 链接以了解更多信息?它将告诉您“可选”部分以及如何实现它。
  • @Someprogrammerdude 不,我没有。感谢您指出。

标签: c++ multithreading locking mutex


【解决方案1】:

这是避免lock_guard 构造函数锁定给定mutex 的一种方法:

std::mutex mtx;
mtx.lock();
std::lock_guard<std::mutex> lck(mtx, std::adopt_lock);

目的是让您的lock_guard 拥有您已锁定的mutex 的所有权。

发件人:https://en.cppreference.com/w/cpp/thread/lock_guard/lock_guard

显式 lock_guard(mutex_type&m); (1)(C++11 起)
lock_guard(mutex_type& m, std::adopt_lock_t t ); (2)(C++11 起)
lock_guard( const lock_guard& ) = 删除; (3)(C++11 起)
获取给定互斥锁 m 的所有权。

1) Effectively calls m.lock(). The behavior is undefined if m is not a recursive mutex and the current thread already owns m.  
2) Acquires ownership of the mutex m without attempting to lock it.  

如果当前线程不拥有 m,则行为未定义。
3) 复制构造函数被删除。
如果 m 在 lock_guard 对象之前被销毁,则行为未定义。

【讨论】:

  • lock_guard(mutex_type&amp; m, std::adopt_lock_t t); 是否检查m 是否被锁定?在没有锁定的情况下,lock_guard::~lock_guard()是否跳过unlock()的调用?我会期待这个。但是,我想知道 cppreference 文档中没有提到它。 (一个 MCVE 的演示会很好。)
  • @Scheff, “如果当前线程不拥有 m,则行为未定义。” - 这里,“不拥有”意味着“没有锁定”。因此,如果您将未锁定的 mutex 传递给 lockguard 构造函数,则会得到未定义的行为。
  • 可能是,我过于关注“可选”。我将问题理解为“如何选择使用lock_guard?”再读一遍我似乎误解了这个......(对不起,我的错。)
猜你喜欢
  • 1970-01-01
  • 2017-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-13
  • 1970-01-01
  • 2021-08-03
相关资源
最近更新 更多