std :: lock仍然导致死锁 [英] std::lock still caused deadlock

查看:451
本文介绍了std :: lock仍然导致死锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: lock用于防止死锁,对吗?但是在我的测试中,它仍然导致死锁.您能检查一下我的测试代码,看看我是否使用不正确?

std::lock is used to prevent deadlock, right? However in my testing, it still caused deadlock. Could you check my test code to see if I used it incorrectly?

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(2));
    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(2));
    std::unique_lock<std::mutex> lock2(m1, std::defer_lock);
    printf("func2 lock m1\n");
    std::lock(m2, m1);
    printf("func2 std lock\n");
}



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

输出为: func1锁m1 func2锁m2 func2锁m1 func1锁m2 func2 std锁定

The output is : func1 lock m1 func2 lock m2 func2 lock m1 func1 lock m2 func2 std lock

然后控制台挂起了...

Then console hung...

推荐答案

我认为您要执行的操作不起作用:您不能在唯一锁下静默修改互斥锁.根据规范,延迟"构造函数将锁防护设置为不拥有",并且您不能更改它:

I think what you're trying to do doesn't work: You cannot silently modify the mutex underneath the unique lock. According to the specification, the "deferred" constructor makes the lock guard "not owning", and you cannot change that:

unique_lock(mutex_type& m, defer_lock_t) noexcept;

效果:构造类型为unique_lock的对象.

后置条件: pm == addressof(m) owns == false .

Postconditions: pm == addressof(m) and owns == false.

修改仅博览会的owns变量的唯一方法是通过作用于唯一锁.唯一锁不会神奇地检查所保持的互斥锁的状态.

The only way to modify the exposition-only owns variable is by acting on the unique lock. The unique lock does not magically inspect the state of the held mutex.

正确的代码应将唯一锁传递给std::lock算法:

The correct code should pass the unique lock to the std::lock algorithm:

std::lock(lock1, lock2);

这篇关于std :: lock仍然导致死锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆