I ran into std::recursive_mutex while trying to debug something today. First let me illustrate. I found some class methods which looked like this:
Gasp! I’m thinking to myself, “Why the heck haven’t I seen a deadlock with this before?”. Clearly function_A() is getting a lock on the mutex, and calling function_B() which locks the mutex again.
“Brock, what is ‘lock_t’?……”
I’m glad you asked, because look what it’s hiding:
typedef std::lock_guard<std::recursive_mutex> lock_t;
Ah ha! A type of mutex I haven’t used before. I wrote a previous post about how knowledge of the standard library is a good thing, and I stand by it, but it looks like there is a lot of push against using recursive locks and for good reason:
In this case, everything worked fine, but until I checked the typedef I was questioning my whole universe! It lead me down a path that I didn’t need to for the bug I was trying to find.
My question is the following….
How do I write code that isn’t going to derail the next programmer that is debugging something? Well, clean coding always helps but in this case those functions above look incredibly clean… thankfully there is an effort from the modern C++ community on Cpp Core Guidelines.
And hey, look at this guideline in the works:
- Prefer non-recursive locks (often used to work around bad reasoning, overhead)