I know my question is quite similar to this Why does std::lock_guard release the lock after using std::adopt_lock?, but the behavior I see is not. This is my code:
#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;
}
And this is the result I get:
fun1
lock mutex
fun2
still holds mutex
Clearly, the unique_lock
in fun1
still holds the mutex. So my question is "Does std::lock_guard
release the mutex after constructed with std::adopt_lock
option?". Hope you all can help me clarify this situation. Thank you.
Aucun commentaire:
Enregistrer un commentaire