2008年7月1日 星期二

Using Mutex Objects

Mutex is a kernel object.

//**************************************
* Sample of how to create Mutex
**************************************//
HANDLE hMutex;

// Create a mutex with no initial owner.

hMutex = CreateMutex(
NULL, // no security attributes
FALSE, // initially not owned
"MutexToProtectDatabase"); // name of mutex

if (hMutex == NULL)
{
// Check for error.
}

//**************************************
* Use WaitForSingleObject to use Mutex
**************************************//

BOOL FunctionToWriteToDatabase(HANDLE hMutex)
{
DWORD dwWaitResult;

// Request ownership of mutex.

dwWaitResult = WaitForSingleObject(
hMutex, // handle to mutex
5000L); // five-second time-out interval

switch (dwWaitResult)
{
// The thread got mutex ownership.
case WAIT_OBJECT_0:
__try {
// Write to the database.
}

__finally {
// Release ownership of the mutex object.
if (! ReleaseMutex(hMutex)) {
// Deal with error.
}

break;
}

// Cannot get mutex ownership due to time-out.
case WAIT_TIMEOUT:
return FALSE;

// Got ownership of the abandoned mutex object.
case WAIT_ABANDONED:
return FALSE;
}

return TRUE;
}