如何多次锁定互斥锁? [重复]

问题描述 投票:0回答:3

例如:

std::mutex g_mutex;


void Function2()
{
    std::lock_guard<std::mutex> lock(g_mutex);

    //do something not thread safe

    printf("in function2: thread: 0x%08X\n", 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%08X\n", std::this_thread::get_id().hash());

    Function2();
}


int main()
{

    std::thread t1([](){

        Function1();

    });
    t1.join();

    getchar();
    return 0;
}

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

R6010 -abord() 已被调用

是否可以仅使用一个互斥锁来做到这一点?我不想创建另一个互斥体

c++ mutex recursive-mutex
3个回答
1
投票

我会使用该函数的解锁版本,并通过在结构/类中将其设为私有来隐藏它:

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%08X\n", std::this_thread::get_id().hash());

        f2_i();
    }

private:
    static void f2_i()
    {
        //do something not thread safe
        printf("in function2: thread: 0x%08X\n", std::this_thread::get_id().hash());
    }
};

1
投票

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

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.