1 声明互斥对象
HANDLE hrtextmutex=NULL;
2 创建锁对象
hrtextmutex = ::CreateMutex(NULL, FALSE, _T("testmutex"));
3 线程函数中用到上面定义的互斥锁对象
DWORD WINAPI testmutextfun(LPVOID param)
{
if (!hrtextmutex)
return 2;
DWORD dwCount = 0, dwWaitResult;
int i = 0;
while (i < 100)
{
dwWaitResult = WaitForSingleObject(hrtextmutex, INFINITE);
switch (dwWaitResult)
{
case WAIT_OBJECT_0:// 成功等候有信号状态
__try{
i++;
char msg[200] = { 0 };
sprintf_s(msg, 200, "\ntestmutextfun i=%d threadid=%d\n", i, ::GetCurrentThreadId());
OutputDebugStringA(msg);
}
__finally{
// 通过ReleaseMutex释放线程拥有的互斥对象所有权,如果不调用这语句,则其它线程获取时因状态丢失而无法获得所有权从而导致同步对象失败
if (!ReleaseMutex(hrtextmutex))
{
OutputDebugStringA("\nReleaseMutex error\n");
}
}
break;
case WAIT_ABANDONED: // 丢失状态
OutputDebugStringA("\nWaitForSingleObject abandoned\n");
return FALSE;
break;
default:
break;
}
}
return TRUE;
}
4 创建2个线程对象,并关闭线程对象
HANDLE hrThreadArr[2] = { 0 };
for (int i = 0; i < 2; i++)
{
hrThreadArr[i] = ::CreateThread(NULL, 0, testmutextfun, NULL, 0, NULL);
if (NULL == hrThreadArr[i])
{
char msg[100] = { 0 };
sprintf_s(msg, 100, "\ncreate thread failed errorcode:%d\n", GetLastError());
OutputDebugStringA(msg);
return;
}
}
WaitForMultipleObjects(2, hrThreadArr, true, INFINITE);
for (int i = 0; i < 2; i++)
{
CloseHandle(hrThreadArr[i]);
}