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

Raymond Chen

Raymond

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.

0 comments

Comments are closed. Login to edit/delete your existing comments