如何多次锁定互斥锁

how to lock a mutex multiple times?

本文关键字:锁定 何多次      更新时间:2023-10-16

例如:

std::mutex g_mutex;

void Function2()
{
    std::lock_guard<std::mutex> lock(g_mutex);
    //do something not thread safe
    printf("in function2: thread: 0x%08Xn", std::this_thread::get_id().hash());
}
void Function1()
{
    std::lock_guard<std::mutex> lock(g_mutex);
    //do something not thread safe
    printf("in function1: thread: 0x%08Xn", std::this_thread::get_id().hash());
    Function2();
}

int main()
{
    std::thread t1([](){
        Function1();
    });
    t1.join();
    getchar();
    return 0;
}

我想通过锁定一个互斥锁来使Function1Function2线程安全,但是会抛出运行时错误:

R6010 - board()已被调用

有可能只使用一个互斥锁吗?我不想再创建一个互斥对象

我将使用该函数的未锁定版本,并通过在struct/class中将其设置为私有来隐藏它:

struct Functions {
public:
    static void f2()
    {
        std::lock_guard<std::mutex> lock(g_mutext);
        f2_i();
    }
    static void f1()
    {
        std::lock_guard<std::mutex> lock(g_mutext);
        //do something not thread safe
        printf("in function1: thread: 0x%08Xn", std::this_thread::get_id().hash());
        f2_i();
    }
private:
    static void f2_i()
    {
        //do something not thread safe
        printf("in function2: thread: 0x%08Xn", std::this_thread::get_id().hash());
    }
};

需要多次锁定同一个互斥锁通常是糟糕设计的标志。

要么重新设计以避免多次锁定同一个互斥锁,要么使用递归互斥锁

确实存在递归互斥锁,但我被告知它们是有问题的。https://groups.google.com/forum/?hl=en#!topic/comp.programming.threads/tcrTKnfP8HI%5B51-75-false%5D和递归锁(互斥锁)与非递归锁(互斥锁)的讨论