首页 > 解决方案 > 如何避免使用 lock_guard 锁定?

问题描述

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

(constructor)
构造一个 lock_guard,可选地锁定给定的互斥锁

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

标签: c++multithreadinglockingmutex

解决方案


这是避免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& ) = delete; (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 对象之前被销毁,则行为未定义。


推荐阅读