user3829524
user3829524

Reputation: 13

how to lock a mutex multiple times?

For example:

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;
}

I want to make Function1 and Function2 thread safe by locking one mutex, but it throws Runtime Error:

R6010 -abord() has been called

is it possible to do that using only one mutex? i don't want to create another mutex

Upvotes: 1

Views: 2815

Answers (3)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136218

The need to lock the same mutex multiple times is generally a sign of a bad design.

Either redesign to avoid locking the same mutex multiple times or use a recursive mutex.

Upvotes: 1

Pete
Pete

Reputation: 4812

I'd use an unlocked version of the function and hide it by making it private in a 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%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());
    }
};

Upvotes: 1

Ben
Ben

Reputation: 9703

There is such thing as a recursive mutex, but I've been told they are considered questionable. https://groups.google.com/forum/?hl=en#!topic/comp.programming.threads/tcrTKnfP8HI%5B51-75-false%5D and Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex) for discussions.

Upvotes: 0

Related Questions