Search code examples
c++mutexrecursive-mutex

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


Solution

  • 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.