CloseHandle on a Mutex, before ReleaseMutex - What

2019-05-05 07:27发布

问题:

If I call CloseHandle on a mutex before a thread has finished with the mutex, and hence, hasn't yet called ReleaseMutex, what is the expected behaviour?

回答1:

The most serious consequence is a thread that's waiting for the mutex getting unblocked. The WaitXxx call returns WAIT_ABANDONED. At which point it would be a really good idea to call TerminateProcess because you have no idea what the hell just happened.



回答2:

CloseHandle() immediately destroys the handle that is passed to it. ReleaseMutex() will then fail with an ERROR_INVALID_HANDLE error code if called with the closed mutex handle.

If the mutex is named, there is a single reference-counted kernel object backing the mutex, but CreateMutex() and OpenMutex() return unique HANDLE values that have to be closed individually. If multiple handles to the same named mutex are created/opened, calling CloseHandle() on one handle does not effect the other handles to the same mutex.



回答3:

CloseHandle() in this case does destroy the handle, but the mutex object is removed from memory only when all its handles have been closed. So, by CloseHandle(handle) you will destroy that handle and so ReleaseMutex(handle) will not work. But, the mutex will still be owned by that thread with no way to release it, affecting other threads waiting for mutex lock.