Using the mutex object and process related functions for thread synchronization

 

 

 

// For WinXp as a target, change appropriately

#define _WIN32_WINNT 0x0501

#include <windows.h>

#include <stdio.h>

 

int wmain(void)

{

// One process creates the mutex object.

HANDLE hMutex, hMutex1;

// char * MName = "MyOwnMutex";

LPCWSTR MName = L"MyOwnMutex";

 

hMutex = CreateMutex(

NULL, // no security descriptor

TRUE, // initially own by calling thread

MName); // object name

if (hMutex == NULL)

wprintf(L"CreateMutex(): error: %d.\n", GetLastError());

else

{

if (GetLastError() == ERROR_ALREADY_EXISTS)

wprintf(L"CreateMutex(): opened existing %s mutex.\n", MName);

else

wprintf(L"CreateMutex(): new %s mutex was successfully created.\n", MName);

}

 

// =======================================

hMutex1 = OpenMutex(

MUTEX_ALL_ACCESS, // request full access

FALSE, // handle not inheritable

MName); // object name

 

if (hMutex1 == NULL)

wprintf(L"OpenMutex() - error: %d.\n", GetLastError());

else

wprintf(L"OpenMutex(): %s mutex was opened successfully.\n", MName);

 

// Release ownership of the mutex object. There is no ownership here...

if (ReleaseMutex(hMutex))

wprintf(L"ReleaseMutex() - mutex object handle was released!\n");

else

wprintf(L"Failed to release mutex object handle, error %d\n", GetLastError());

return 0;

}

 

 

Output example:

 

CreateMutex(): new MyOwnMutex mutex was successfully created.

OpenMutex(): MyOwnMutex mutex was opened successfully.

ReleaseMutex() - mutex object handle was released!

Press any key to continue . . .

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Target platform: none, just for learning and fun

Header file: Standard and Windows

Additional library: Windows Platform SDK

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: non-CLR or unmanaged

To do: Using the Windows mutex and process related functions for thread synchronization

To show: The Windows process and thread related functions usage

 

 

C and C++ Programming Resources | C & C++ Code Example Index