简体   繁体   English

Std::Lock 避免了死锁,但是这个程序卡住了

[英]Std::Lock avoids deadlock but this program gets stuck

All, Referring to the question in std::lock still caused deadlock全部,参考std::lock 中的问题仍然导致死锁

I still couldn't figure what is the problem in the below code.我仍然无法弄清楚以下代码中的问题。 Can somebody please explain the problem and how to fix this?有人可以解释这个问题以及如何解决这个问题吗? Why does it get hung?为什么会挂? Pls help.请帮忙。

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

std::mutex m1;
std::mutex m2;

void func1()
{
    std::unique_lock<std::mutex> lock1(m1, std::defer_lock);
    printf("func1 lock m1\n");
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::unique_lock<std::mutex> lock2(m2, std::defer_lock);
    printf("func1 lock m2\n");
    std::lock(m1, m2);
    printf("func1 std lock\n");

}

void func2()
{
    std::unique_lock<std::mutex> lock1(m2, std::defer_lock);
    printf("func2 lock m2\n");
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::unique_lock<std::mutex> lock2(m1, std::defer_lock);
    printf("func2 lock m1\n");
    std::lock(m1, m2);
    printf("func2 std lock\n");
}



int main(int argc,char* argv[])
{
    std::thread th1(func1);
    std::thread th2(func2);
    th1.join();
    th2.join();
    return 0;
}

Output seen: func1 lock m1 Output 看到: func1 lock m1
func2 lock m2 func2锁m2
func1 lock m2 func1锁m2
func1 std lock func1 标准锁
func2 lock m1 func2锁m1
----- Hung here. -----挂在这里。

Why doesn't func2 proceed even though func1 has released both the mutexes?即使 func1 已经释放了两个互斥体,为什么 func2 不继续?

Instead of:代替:

std::lock(m1, m2);

use:利用:

std::lock(lock1, lock2);

More details (including an example) can be found on the reference page for std::lock .更多详细信息(包括示例)可以在std::lock的参考页面上找到。

Why does your code hang?为什么你的代码挂起?

When you call std::lock(m1, m2) , the two mutexes are locked directly.当您调用std::lock(m1, m2)时,两个互斥锁被直接锁定。 Neither of the std::unique_lock s ( lock1 and lock2 ) are aware of this, and thus they can not unlock the mutexes. std::unique_locklock1lock2 )都没有意识到这一点,因此它们无法解锁互斥锁。

So, when func1 ends both mutexes are still locked, and func2 cannot proceed past the std::lock(m1, m2) line.因此,当func1结束时,两个互斥锁仍处于锁定状态,并且func2无法继续通过std::lock(m1, m2)行。

Why does the fixed code work?为什么固定代码有效?

When you call std::lock(lock1, lock2) , the std::unique_lock s ( lock1 and lock2 ) are aware of this - they now own the locks, and are responsible for unlocking them (which happens when they go out of scope).当您调用std::lock(lock1, lock2)时, std::unique_lock s( lock1lock2 )知道这一点 - 它们现在拥有锁,并负责解锁它们(当它们 go 超出范围时会发生这种情况)。

So, when func1 ends both mutexes are unlocked, and func2 can proceed past the std::lock(lock1, lock2) line.因此,当func1结束时,两个互斥锁都被解锁,并且func2可以继续通过std::lock(lock1, lock2)行。 And all is well.一切都很好。

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

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