互斥锁锁定和解锁序列

时间:2020-10-20 21:19:30

标签: mutex

使用以下互斥锁示例是否有意义,还是应该先解锁“ A”然后再锁定“ B”?

mtx.lock(A);
mtx.lock(B);
//code
mtx.unlock(A);
mtx.unlock(B);

如果我按说明使用它,可能是什么问题?

1 个答案:

答案 0 :(得分:0)

如果有多个互斥锁,则可以分别锁定和解锁它们。 您必须始终警惕1)死锁和2)发生异常的可能性,这些异常会阻止互斥锁解锁

try{
    mtx.lock(A);
    THREAD_CALLS_FUNCTION(S) // Woops... an exception is thrown
    mtx.unlock(A); // not happening.
{ catch (...)
{
    (...) // but this is executed, mutex remains locked
}

还有更多风险,请参见https://www.modernescpp.com/index.php/the-risk-of-mutexes

一个好的做法是将互斥锁与 locks (可能是std::lock_guard)结合使用。它们以更安全的方式封装互斥量。僵局。 here对此进行了更详细的讨论。