【问题标题】:Mutex lock and unlock sequence互斥锁和解锁序列
【发布时间】:2021-02-03 18:31:55
【问题描述】:

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

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

如果我按照描述使用它,可能会出现什么问题?

【问题讨论】:

标签: mutex


【解决方案1】:

如果您有多个互斥锁,您可以分别锁定和解锁它们。 您必须时刻警惕 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

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

【讨论】:

    猜你喜欢
    • 2018-05-23
    • 1970-01-01
    • 2022-07-31
    • 2010-12-17
    • 1970-01-01
    • 2021-11-23
    • 2010-11-22
    • 2021-12-23
    相关资源
    最近更新 更多