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

ParameterDescription
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

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;
}

See Also