HANDLE hMutex;
h = CreateMutex
(
NULL,
// no security attributes
FALSE,
// initially not owned
"MutexToProtectDatabase");
// name of mutex
if (hMutex == NULL)
{
// Check for error.
}
When a thread of this process writes to the database, it first requests ownership of the mutex. If it gets ownership, the thread writes to the database and then releases its ownership.
The example uses the try-finally structured exception-handling syntax to ensure that the thread properly releases the mutex object. To prevent the mutex object from being abandoned inadvertently, the finally block of code is executed no matter how the try block terminates — unless the try block includes a call to the TerminateThread function.
BOOL FunctionToWriteToDatabase(HANDLE hMutex)
{
DWORD dwWaitResult;
dwWaitResult = WaitForSingleObject(
hMutex,
// handle of mutex
5000L);
// five-second time-out interval
switch (dwWaitResult)
{
case WAIT_OBJECT_0:
try
{
// Write to the database.
}
finally
{
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;
}
上面是一个数据库同步的例子,当一个线程获得Mutex时另一个必须等待。。应该可以满足你的要求