开发者

CloseHandle on a Mutex, before ReleaseMutex - What happens?

开发者 https://www.devze.com 2023-02-11 12:58 出处:网络
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开发者_StackOverflow expected behaviour?CloseHandle() immediately d

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开发者_StackOverflow expected behaviour?


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消