c++ - 如何避免使用 lock_guard 锁定?

标签 c++ multithreading locking mutex

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

(constructor)
constructs a lock_guard, optionally locking the given mutex

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

最佳答案

这是避免 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

explicit lock_guard( mutex_type& m ); (1) (since C++11)
lock_guard( mutex_type& m, std::adopt_lock_t t ); (2) (since C++11)
lock_guard( const lock_guard& ) = delete; (3) (since C++11)
Acquires ownership of the given mutex 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.  

The behavior is undefined if the current thread does not own m.
3) Copy constructor is deleted.
The behavior is undefined if m is destroyed before the lock_guard object is.

关于c++ - 如何避免使用 lock_guard 锁定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54033896/

相关文章:

c# - 如果第一个代码正在执行,如何等待?

c - 带有 sscanf 和线程的 sigpipe

C pthreads : Start a Thread from main

c - C中的细粒度锁定

javascript - 如何锁定由nodejs中的多个异步方法共享的对象?

c++ - 使用VTK绘制不同颜色的点

c++ - 什么是关联容器?

c++ - 花括号和圆括号之间的参数评估顺序

c++ - 链接器因重复符号而失败