1

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

user3829524
  • 13
  • 2
  • 5
  • 1
    The obvious solution is to put the code needing the protection in a separate block, so the scope of the lock will expire when done. Locks should be held as little and as short as possible. If you're calling another function which needs to lock on the same mutex, then you must unlock it first. That's how (normal) mutexes are designed. – Some programmer dude Jul 11 '14 at 13:35

3 Answers3

1

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());
    }
};
Pete
  • 4,784
  • 26
  • 33
1

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.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
0

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.

Community
  • 1
  • 1
Ben
  • 9,184
  • 1
  • 43
  • 56