我知道我的问题与此非常相似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
infun1
仍然持有互斥锁。所以我的问题是“使用选项std::lock_guard
构造后是否释放互斥锁?”。std::adopt_lock
希望大家能帮我澄清一下这种情况。谢谢你。