Jan 252016
 

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:

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:

http://www.zaval.org/resources/library/butenhof1.html
http://www.codingstandard.com/rule/18-3-3-do-not-use-stdrecursive_mutex/
https://cppwisdom.quora.com/Recursive-mutexes-considered-harmful

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)

 

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

(required)

(required)