在 ReleaseMutex 之前 CloseHandle 互斥锁 - 会发生什么?
如果我在线程完成互斥体之前对互斥体调用 CloseHandle,因此尚未调用 ReleaseMutex,那么预期的行为是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
CloseHandle()
立即销毁传递给它的句柄。如果使用关闭的互斥体句柄调用,ReleaseMutex()
将失败并返回ERROR_INVALID_HANDLE
错误代码。如果互斥体已命名,则有一个引用计数内核对象支持该互斥体,但
CreateMutex()
和OpenMutex()
返回唯一的HANDLE
必须单独关闭的值。如果创建/打开同一命名互斥体的多个句柄,则在一个句柄上调用 CloseHandle() 不会影响同一互斥体的其他句柄。CloseHandle()
immediately destroys the handle that is passed to it.ReleaseMutex()
will then fail with anERROR_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()
andOpenMutex()
return uniqueHANDLE
values that have to be closed individually. If multiple handles to the same named mutex are created/opened, callingCloseHandle()
on one handle does not effect the other handles to the same mutex.最严重的后果是线程正在等待互斥锁被解除阻塞。 WaitXxx 调用返回 WAIT_ABANDONED。此时调用 TerminateProcess 是一个非常好的主意,因为您不知道刚刚发生了什么。
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() 确实会销毁句柄,但只有当所有句柄都已关闭时,互斥对象才会从内存中删除。
因此,通过 CloseHandle(handle) 您将销毁该句柄,因此 ReleaseMutex(handle) 将不起作用。但是,互斥锁仍然由该线程拥有,无法释放它,从而影响等待互斥锁的其他线程。
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.