visual-c++ - 互斥体根本没有释放

标签 visual-c++ mutex

我想要运行一个 .exe 实例,并且正在使用互斥锁,如下所示 app::InitInstance()

hMutex = OpenMutex(MUTEX_ALL_ACCESS, 0, _T("app.0"));
if (!hMutex)
    hMutex = CreateMutex(0, 0, _T("app.0"));

app::ExitInstance() 中我有

int iii = ReleaseMutex(hMutex);

其中 hMutex 是全局变量:HANDLE hMutex;

此方法有效,并且仅将应用程序限制为一个实例。但是,关闭后,我使用 GetLastError() 收到以下消息:“尝试释放调用者不拥有的互斥体。”

最佳答案

http://msdn.microsoft.com/en-us/library/windows/desktop/ms682411(v=vs.85).aspx

Remarks

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

A thread obtains ownership of a mutex either by creating it with the bInitialOwner parameter set to TRUE or by specifying its handle in a call to one of the wait functions. When the thread no longer needs to own the mutex object, it calls the ReleaseMutex function so that another thread can acquire ownership.

A thread can specify a mutex that it already owns in a call to one of the wait functions without blocking its execution. This prevents a thread from deadlocking itself while waiting for a mutex that it already owns. However, to release its ownership, the thread must call ReleaseMutex one time for each time that it obtained ownership (either through CreateMutex or a wait function).

还有

HANDLE WINAPI CreateMutex(
  _In_opt_  LPSECURITY_ATTRIBUTES lpMutexAttributes,
  _In_      BOOL bInitialOwner,
  _In_opt_  LPCTSTR lpName
);

关于visual-c++ - 互斥体根本没有释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25927639/

相关文章:

visual-c++ - WinCE : How can I determine the module that contains a code address?

c++ - 安卓 NDK 互斥量

c - 在C中使用互斥锁同步pthread

c++ - static_cast 动态_cast : expected constant expression?

c++ - 在 VC++ 中确定未初始化的变量

c++ - 在 IMMDeviceEnumerator 上调用 SAFE_RELEASE 时崩溃

c - 从 VC++ 2008 编译器读取控制台输入 :Error

linux - linux' "mutex lock"是使用 "memory barrier"实现的吗?

c++ - 协助对 pthread_cond_wait() 的错误理解

c++ - boost mutex, condition, scoped_lock ,我在这里用错了吗?