类似于临界段,互斥量能够保证对单个资源的互斥访问,互斥量包含一个使用数量、一个线程ID、一个递归计数器。
//创建互斥量
HANDLE CreateMutex(PSECURITY_ATTRIBUTES psa, BOOL fInitialOwner, PCTSTR pszName);
//获得它自己进程与现有互斥量相关的句柄
HANDLE OpenMutex(DWORD fdwAccess, OOL fInherit, PCTSTR pszName);
//使互斥量递归计数减1,减为0的时候,恢复已通知状态
ReleaseMutex(HANDLE hMutex);
线程通过WaitForSingleObject或者WaitForMultipleObjects来等待互斥量,若线程成功的获得了互斥量,那么互斥量中的线程ID将记录该线程的ID,并递归计数加1
应用举例:
DWORD WINAPI ThreadFuncMutex1(PVOID pParam)
{
HANDLE* pMutex = (HANDLE*)pParam;
for (int i=0; i <= 10; i++)
{
WaitForSingleObject(*pMutex, INFINITE);
cout << "Thread1 output:" << i <<endl;
ReleaseMutex(*pMutex);
}
return 0;
}
DWORD WINAPI ThreadFuncMutex2(PVOID pParam)
{
HANDLE* pMutex = (HANDLE*)pParam;
for (int i=0; i <= 10; i++)
{
WaitForSingleObject(*pMutex, INFINITE);
cout << "Thread2 output:" << i <<endl;
ReleaseMutex(*pMutex);
}
return 0;
}
int main()
{
HANDLE hMutex = CreateMutex(NULL, false, L"Display Mutex");
HANDLE tHandle1 = CreateThread(NULL, 0, ThreadFuncMutex1, &hMutex, 0, NULL);
HANDLE tHandle2 = CreateThread(NULL, 0, ThreadFuncMutex2, &hMutex, 0, NULL);
HANDLE handles[] = {tHandle1, tHandle2};
WaitForMultipleObjects(2, handles, true, INFINITE);
CloseHandle(hMutex);
return 0;
}