简体   繁体   English

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

[英]Does std::lock_guard release the mutex after constructed with std::adopt_lock option?

I know my question is quite similar to this Why does std::lock_guard release the lock after using std::adopt_lock?我知道我的问题与此非常相似为什么 std::lock_guard 在使用 std::adopt_lock 后释放锁? , but the behavior I see is not. ,但我看到的行为不是。 Here 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.显然, fun1unique_lock仍然持有互斥锁。 So my question is "Does std::lock_guard release the mutex after constructed with std::adopt_lock option?".所以我的问题是“使用std::adopt_lock选项构造后, std::lock_guard是否释放互斥锁?”。 Hope you all can help me clarify this situation.希望大家能帮我澄清一下这个情况。 Thank you.谢谢你。

When you constructed a std::unique_lock to manage the mutex, you should stick to it unless you first break the association of the std::unique_lock with the mutex using std::unique_lock::release .当您构造一个std::unique_lock来管理互斥锁时,您应该坚持使用它,除非您首先使用std::unique_lock::release断开std::unique_lock与互斥锁的关联。 In your sample, you touched the raw mutex when it's still managed by a std::unique_lock and this is wrong.在您的示例中,您在原始互斥锁仍由std::unique_lock管理时触及了它,这是错误的。

The program has undefined behavior.该程序具有未定义的行为。

You've created two guards that both think they own the mutex and they will both unlock it.您已经创建了两个守卫,他们都认为他们拥有mutex ,并且都会unlock它。 That's UB.那是UB。

Using m.lock() in fun1 instead of using a guard would be one way to make it have defined behavior.fun1使用m.lock()而不是使用守卫将是使其具有定义行为的一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM