c++ - 使用 std::adopt_lock 选项构造后,std::lock_guard 是否释放互斥锁?

标签 c++ multithreading c++11 mutex unique-lock

我知道我的问题与此非常相似 Why does std::lock_guard release the lock after using std::adopt_lock? ,但我看到的行为不是。这是我的代码:

#include <mutex>
#include <iostream>
using namespace std;

std::mutex m;
void fun2();
void fun1() {
    cout << "fun1" << endl;
    std::unique_lock<std::mutex> guard(m);
    cout << "lock mutex" << endl;
    fun2();
    if (guard.owns_lock()) {
        cout << "still holds mutex" << endl;
    }
    else {
        cout << "doesn't hold mutex" << endl;
    }
}
void fun2() {
    std::lock_guard<std::mutex> guard(m, std::adopt_lock);
    cout << "fun2" << endl;
}
int main(int argc, char* argv[]) {
    fun1();
    return 0;
}
这是我得到的结果:
fun1
lock mutex
fun2
still holds mutex
显然,unique_lockfun1仍然持有互斥锁。所以我的问题是“使用 std::lock_guard 选项构造后 std::adopt_lock 是否释放互斥锁?”。希望大家能帮我澄清一下这个情况。谢谢你。

最佳答案

当您构建 std::unique_lock 时要管理互斥锁,你应该坚持下去,除非你首先打破了 std::unique_lock 的关联。与互斥使用 std::unique_lock::release .在您的示例中,当原始互斥锁仍由 std::unique_lock 管理时,您触及了它。这是错误的。

关于c++ - 使用 std::adopt_lock 选项构造后,std::lock_guard 是否释放互斥锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69565125/

相关文章:

c# - 将列表传递给任务

c++ - 即使一切看起来都是 "good", std::mutex::lock 也会抛出吗?

c++ - 如何解释 Variadic 模板中的继承?

c++ - 使用 make 编译多个可执行文件

c++ - 如何简洁地编写 'switch' 语句来猜测用户正在考虑的数字

c++ - QComboBox动态项目列表

java:为什么主线程等待子线程完成

C++ : How to use SocketAppender of log4cplus to send logs to logstash server?

Java集群,只运行一次任务

c++ - 数组中可变大小对象可能无法初始化的问题