December 8th, 2016

What is this race condition that the OpenMutex documentation is trying to warn me about?

A customer asked for clarification on what they considered an enigmatic sentence in the documentation for the Open­Mutex function:

If your multithreaded application must repeatedly create, open, and close a named mutex object, a race condition can occur. In this situation, it is better to use Create­Mutex instead of Open­Mutex, because Create­Mutex opens a mutex if it exists and creates it if it does not.

“What is this race condition the documentation is talking about? Our program uses Open­Mutex and we are wondering if we should switch to Create­Mutex.”

Consider two threads. One thread calls Create­Mutex, then Close­Handle, then Create­Mutex, then Close­Handle, then Create­Mutex, then Close­Handle, and so on.

The other thread calls Open­Mutex.

The race condition is that the second thread’s call to Open­Mutex will fail if it takes place after the first thread calls Close­Handle and before it gets to make its next call to Create­Mutex.

One of my colleagues couldn’t understand why MSDN bothers to say anything about this situation at all. “You can’t open a mutex that doesn’t exist. Duh. I think this adds more confusion than it helps.”

I suspect the reason why MSDN bothers to say anything about this is that there was a customer who had two threads. One thread calls Create­Mutex, then Close­Handle, then Create­Mutex, then Close­Handle, then Create­Mutex, then Close­Handle, and so on. The other thread calls Open­Mutex.

This customer found that if the second thread calls Open­Mutex at an inopportune time, the call fails. They then insisted that something be added to the documentation to state explicitly that a bad idea is a bad idea. Probably because they needed something in writing to show their management in order to justify the time they are going to need to spend fixing the bug.

Once again, MSDN has been forced into being a pawn in some company’s internal politics.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.