Reputation: 35
I would like to have one instance of an .exe running and am using mutex as follows in app::InitInstance()
hMutex = OpenMutex(MUTEX_ALL_ACCESS, 0, _T("app.0"));
if (!hMutex)
hMutex = CreateMutex(0, 0, _T("app.0"));
In app::ExitInstance()
I have
int iii = ReleaseMutex(hMutex);
where hMutex is a global variable: HANDLE hMutex;
This works and only limits the app to one instance. However, upon closing I get the following message using GetLastError()
: "Attempt to release mutex not owned by caller."
Upvotes: 2
Views: 724
Reputation: 18411
Ownership or release of mutex is not required in this case, since you aren't doing any resource protection. You may, however, issue a CloseHandle
on it - which will decrease the reference count, and when last handle is closed, the mutex object will be destroyed. You, don't need to call it either, as OS will do it for you (and would maintain reference counting mechanism also).
You may, however, need to close it as soon as possible, when second instance is running (possibility displaying a dialog box). In this case, just before displaying the dialog (that "Another instance is running"), you must close it. If you don't do, consider a scenario:
Upvotes: 1
Reputation: 5728
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).
And
HANDLE WINAPI CreateMutex(
_In_opt_ LPSECURITY_ATTRIBUTES lpMutexAttributes,
_In_ BOOL bInitialOwner,
_In_opt_ LPCTSTR lpName
);
Upvotes: 1