What happens if I ReleaseMutex() twice?

c++, multithreading, mutex, winapi

Solution

peejay provided a good link in his comment to the ReleaseMutex documentation. I believe that this line from the documentation answers your question:

The ReleaseMutex function fails if the calling thread does not own the mutex object.

While it is not explicitly said, I think that releasing a mutex (the first time) causes the calling thread to no longer own the mutex object. Thus the second call will simply fail. Such an implementation would make sense too since it would allow easily detecting this type of error (Just check the return value).

Problem

The Microsoft documentation is silent about what happens if I mistakenly call `ReleaseMutex()` when the mutex is already unlocked. Details: I'm trying to fix up some Windows code without having access to the compiler. I realise that WinApi mutexes are all recursive, and reference-counted. If I were making use of that feature, it's obvious that the extra `ReleaseMutex()` call would prematurely decrement the reference counter. However, the code that I am looking at does not use the mutex recursively, so the reference count never gets higher than '1'. It does release the mutex more times than necessary... so what happens? Does the reference count go negative? Does it stay at zero (unlocked) and just return an ignorable error? (Naturally, this code doesn't actually check for errors when it calls these functions!)

Original source