CreateMutex
Namespace: WinBase.h
Header: synchapi.h
Synopsis
HANDLE CreateMutexA(
LPSECURITY_ATTRIBUTES lpMutexAttributes,
BOOL bInitialOwner,
LPCSTR lpName
);
HANDLE CreateMutexW(
LPSECURITY_ATTRIBUTES lpMutexAttributes,
BOOL bInitialOwner,
LPCWSTR lpName
);
#ifdef UNICODE
#define CreateMutex CreateMutexW
#else
#define CreateMutex CreateMutexA
#endif
Parameters
| Parameter | Description |
|---|---|
lpMutexAttributes |
Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. NULL for default. |
bInitialOwner |
If TRUE, the calling thread obtains immediate ownership of the mutex. |
lpName |
Optional name of the mutex object. Must be NULL or a null‑terminated string. If a mutex with the same name exists, the function opens a handle to the existing mutex. |
Return Value
If the function succeeds, the return value is a handle to the newly created mutex object. If the function fails, the return value is NULL. Call GetLastError for extended error information.
Remarks
- A mutex can be used for inter‑process synchronization when created with a name.
- To release ownership, call
ReleaseMutex. Failing to release a mutex results in a deadlock. - When the last handle to a mutex is closed, the system destroys the mutex object.
Example
#include <windows.h>
#include <stdio.h>
int main(void)
{
HANDLE hMutex = CreateMutexA(
NULL, // default security attributes
FALSE, // not owned initially
"Global\\MyMutex"
);
if (hMutex == NULL) {
printf("CreateMutex failed: %lu\n", GetLastError());
return 1;
}
// Wait for ownership
DWORD dwWait = WaitForSingleObject(hMutex, INFINITE);
if (dwWait == WAIT_OBJECT_0) {
printf("Mutex acquired, doing work...\\n");
// Critical section
Sleep(2000);
ReleaseMutex(hMutex);
}
CloseHandle(hMutex);
return 0;
}