Sobes.tech
Junior — Middle

What are the consequences of attempting to re-lock the same std::mutex inside a thread?

sobes.tech AI

Answer from AI

Attempting to lock the same std::mutex again within the same thread will lead to a deadlock, because std::mutex does not support recursive locking. The thread will wait for the mutex to be released, but since it has already locked it and cannot continue, the program will hang.

If you need the ability to lock the same mutex multiple times within the same thread, you should use std::recursive_mutex, which allows a thread to lock the mutex multiple times, but requires an equal number of unlock() calls.

An example with std::mutex will cause a deadlock:

std::mutex mtx;
mtx.lock();
mtx.lock(); // deadlock here

With std::recursive_mutex, this is permissible.