我知道我的问题与此非常相似 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_lock
在 fun1
仍然持有互斥锁。所以我的问题是“使用 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/