std::lock_guard does not lock the mutex as expected

112 views Asked by At

In the following example, func should hang because it attempts to get a lock after main:

#include <cstdio>
#include <mutex>

std::mutex myMutex;

void func(void)
{
    std::lock_guard<std::mutex> lock(myMutex);
    std::printf("WTF somehow got lock!!!\n"); 
}


int main()
{
    std::lock_guard<std::mutex> lock(myMutex);
    // Mutex is locked here.

    func();
}

Yet, when I run it func somehow gets the lock. Why is my C++ not working? Thanks.

1

There are 1 answers

11
user17732522 On

Trying to lock a std::mutex in a given thread that is already locked by the same thread has undefined behavior.

One can use std::recursive_mutex in such a situation instead, but that won't deadlock either. It will instead nest the locks for the thread and make the mutex available for locking by other threads when all nested locks are lifted.

It would be pointless to require such a use to cause a deadlock. Deadlocks are not a valid program state. Threads completely stuck in deadlock are not useful. The standard library is permitted to diagnose a deadlock condition and raise an exception if it would occur (e.g. in a mutex .lock() or thread's .join()). It may also be considered UB for violation of the forward progress guarantees (I am not sure atm).