Using the WaitForSingleObject() function and a mutex object in C program example
// For WinXp as a target, change appropriately
#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <stdio.h>
BOOL FunctionToWriteSomeData(HANDLE hMutex)
{
DWORD dwWaitResult;
// Request the ownership of mutex...
dwWaitResult = WaitForSingleObject(
hMutex, // handle to mutex
5000L); // five-second time-out interval
switch (dwWaitResult)
{
// The thread got the mutex ownership...
case WAIT_OBJECT_0:
// A simple structured exception handling (SEH)...
__try {
printf("The mutex is signaled.\n");
// TODO: Write some data...
}
__finally {
// Release the ownership of the mutex object.
if (!ReleaseMutex(hMutex))
{
// Deal with the error.
printf("ReleaseMutex() failed.\n");
ExitProcess(0);
}
}
// Cannot get the mutex ownership due to time-out.
case WAIT_TIMEOUT:
{
printf("Time-out interval elapsed, and the object's state is signaled (not owned).\n");
printf("Cannot get the mutex ownership\n\n");
return FALSE;
}
// Got the ownership of the abandoned mutex object.
case WAIT_ABANDONED:
{
printf("The mutex is set to non-signaled (owned).\n");
printf("Got the mutex...\n");
return FALSE;
}
}
return TRUE;
}
// ===================================
int main(void)
{
HANDLE hMutex;
BOOL Test;
// Create a mutex with no initial owner.
hMutex = CreateMutex(
NULL, // no security attributes
FALSE, // initially not owned
L"MutexToProtectSomeData"); // name of mutex
if (hMutex == NULL)
{
// Check for error...
printf("CreateMutex() failed, error: %d.\n", GetLastError());
}
else
printf("CreateMutex() is OK.\n");
// Write some data function call...
Test = FunctionToWriteSomeData(hMutex);
// Verify the returned value
printf("The function returned value: %d.\n", Test);
return 0;
}
Output example:
CreateMutex() is OK.
The mutex is signaled.
Time-out interval elapsed, and the object's state is signaled (not owned).
Cannot get the mutex ownership
The function returned value: 0.
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 WaitForSingleObject() function and mutex object for thread synchronization
To show: The Windows process and thread related functions usage in C programming