首页 > 解决方案 > 在代码的其他部分中使用与 lock_gard 相同的互斥锁是否安全?

问题描述

我有下面的命名空间 func1 和 func2 将从不同的线程中调用。

#include<thread>
namespace test{

    std::mutex mu;

    void func1(){
        std::lock_guard<mutex>lock(mu);
       //the whole function needs to be protected
    }

    void func2() {
        mu.lock();
        //some code that should not be executed when func1 is executed
        mu.unlock();
        //some other code
    }
}

使用这个互斥锁(一旦使用 lock_guard 和它之外)来保护这些关键部分是否安全?如果不是如何实现这个逻辑?

标签: c++multithreadingthread-safetymutexraii

解决方案


是的,您可以有效地混合和匹配具有不同功能的不同保护实例(例如 lock_guard、unique_lock 等...)std::mutex。我偶尔遇到的一种情况是,当我想使用std::lock_guard大多数方法时,但使用 std::condition_variable期望std::unique_lock它的wait方法使用 a。

为了详细说明 Oblivion 所说的内容,我通常会在函数中引入一个新的范围块,以使 ofstd::lock_guard的使用保持一致。例子:

void func2() {

    {  // ENTER LOCK
        lock_guard<std::mutex> lck;

       //some code that should not be executed when func1 is executed

    } // EXIT LOCK

    // some other (thread safe) code 
}

使用上述模式的优点是,如果任何东西在处于锁定状态的代码的关键部分内引发异常,lck仍然会调用 的析构函数,从而解锁互斥锁。


推荐阅读