定义:
HANDLE s_hmutexSocket;
对 CreateMutex 等的返回值进行必要的判断
调用OpenMutex时,系统将扫描所有现存的互斥量,如果找到lpName指定的互斥量。
就返回给调用线程,如果找不到就返回NULL
// Create the mutex
CString strMutexName;
strMutexName.Format(_T("OctO_API_Client_Parameter_%d_MUTEX"), (LPARAM)this);
// Parameter
s_hmutexParameter = OpenMutex(MUTEX_ALL_ACCESS, FALSE, strMutexName);
if (NULL == s_hmutexParameter)
s_hmutexParameter = CreateMutex(NULL, FALSE, strMutexName);
else
{
// already defined
_ASSERTE(FALSE);
}
_ASSERTE(s_hmutexParameter);
// Socket
strMutexName.Format(_T("OctO_API_Client_Socket_%d_MUTEX"), (LPARAM)this);
s_hmutexSocket = OpenMutex(MUTEX_ALL_ACCESS, FALSE, strMutexName);
if (NULL == s_hmutexSocket)
s_hmutexSocket = CreateMutex(NULL, FALSE, strMutexName);
else
{
// already defined
_ASSERTE(FALSE);
}
_ASSERTE(s_hmutexSocket);
OpenMutex和CreateMutex后s_hmutexSocket是有信号状态
等待:
WaitForSingleObject(s_hmutexSocket, INFINITE);
具体操作。。。
释放:
ReleaseMutex(s_hmutexSocket);
析构
// Clean up the mutex
// Parameter
if (s_hmutexParameter)
{
CloseHandle(s_hmutexParameter);
s_hmutexParameter = NULL;
} // if (s_hmutexParameter)
// Socket
if (s_hmutexSocket)
{
CloseHandle(s_hmutexSocket);
s_hmutexSocket = NULL;
} // if (s_hmutexSocket)
//
//
//
//
MSDN中的一个例子:
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.
}
When a thread of this process writes to the database, as in the next example, 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 structured exception-handling syntax to ensure that the thread properly releases the mutex object. 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). This prevents the mutex object from being abandoned inadvertently.
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;
}