The Windows process, thread and mutex object C program example

 

 

 

 

// For WinXp as a target, change appropriately

#define _WIN32_WINNT 0x0501

#include <windows.h>

#include <stdio.h>

 

// A mutex object is a synchronization object whose state is set to signaled

// when it is not owned by any thread, and nonsignaled when it is owned. Only

// one thread at a time can own a mutex object, whose name comes from the fact

// that it is useful in coordinating mutually exclusive access to a shared resource.

// For example, to prevent two threads from writing to shared memory at the same time,

// each thread waits for ownership of a mutex object before executing the code that

// accesses the memory. After writing to the shared memory, the thread releases the

// mutex object. A thread uses the CreateMutex function to create a mutex object.

// The creating thread can request immediate ownership of the mutex object and can

// also specify a name for the mutex object. It can also give the mutex a name or create an unnamed mutex.

 

int wmain(void)

{

// One process creates the mutex object.

HANDLE hMutex;

LPCWSTR MName = L"MyMutex";

 

// creates or opens a named mutex object.

hMutex = CreateMutex(

NULL, // no security descriptor

TRUE, // the calling thread obtains initial ownership of the mutex object

MName); // object name

 

if (hMutex == NULL)

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

else

{

if (GetLastError() == ERROR_ALREADY_EXISTS)

wprintf(L"CreateMutex() already exist, opening the existing %s mutex.\n", MName);

else

wprintf(L"CreateMutex(): new mutex object named %s successfully created.\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 mutex object named MyMutex successfully created.

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: To create the Windows mutex object in C program example

To show: The Windows process and thread related functions for mutex object creation

 

 

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