c++ - 如何避免使用 lock_guard 锁定?
问题描述
https://en.cppreference.com/w/cpp/thread/lock_guard
(constructor)
构造一个 lock_guard,可选地锁定给定的互斥锁
如果它是可选的,那么避免锁定的方法是什么?
解决方案
这是避免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 对象之前被销毁,则行为未定义。
推荐阅读
- javascript - 如何使用 ajax 和 php 填充表格并在表格行中添加按钮?
- asp.net - 将 ASP.NET Razor Pages 路由约定添加到具有验证的文件夹中的所有 razor 页面
- windows - 尝试从文件名中批量删除不可见的特殊字符
- c# - 在 C# 中,有没有办法在 CLR 异常期间写入 CPU 寄存器?
- shell - 如何获取日期/时间字符串和当前时间之间的差异?
- python - 如何在多类分类问题的 5 倍交叉验证后绘制 ROC 曲线?
- c# - 如何获取 SOAP 元素值
- powershell - 如何根据数字占位符将值转换为 KB、MB 或 GB?
- networking - HTTP-GET 方法在浏览器和 POSTMAN 桌面应用程序中返回不同的结果?
- python - 将条件应用于分组数据