C++死锁解决心得(二)

2014-11-24 11:08:48 · 作者: · 浏览: 1
ntInfo += strThreadID;
strPrintInfo += _T(" EnterCriticalSection(&cs1)");

PrintString(strPrintInfo);

Sleep(500);
EnterCriticalSection(&cs2);

strPrintInfo = _T("");
strPrintInfo += _T("Thread1 ");
strPrintInfo += strThreadID;
strPrintInfo += _T(" EnterCriticalSection(&cs2)");

PrintString(strPrintInfo);

LeaveCriticalSection(&cs2);
LeaveCriticalSection(&cs1);
}

return 1;
}

DWORD WINAPI Thread2(LPVOID lpParameter)
{
CString strThreadID = _T("");
strThreadID.Format(_T("%d"), GetCurrentThreadId());

CString strPrintInfo = _T("");

for (int i = 0; i < 5; i++)
{
EnterCriticalSection(&cs2);

strPrintInfo = _T("");
strPrintInfo += _T("Thread2 ");
strPrintInfo += strThreadID;
strPrintInfo += _T(" EnterCriticalSection(&cs2)");

PrintString(strPrintInfo);

Sleep(500);

EnterCriticalSection(&cs1);

strPrintInfo = _T("");
strPrintInfo += _T("Thread2 ");
strPrintInfo += strThreadID;
strPrintInfo += _T(" EnterCriticalSection(&cs1)");

PrintString(strPrintInfo);

LeaveCriticalSection(&cs1);
LeaveCriticalSection(&cs2);
}

return 1;
}

运行结果如下。

五、 死锁修改
线程互斥进行修改,Thread1与Thread2对关键代码段的进入与退出顺序改为相同。程序运行正常。
修改后线程代码。
[cpp]
DWORD WINAPI Thread1(LPVOID lpParameter)
{
for (int i = 0; i < 5; i++)
{
EnterCriticalSection(&cs1);
Sleep(500);
EnterCriticalSection(&cs2);

PrintString(_T("Thread1"));

LeaveCriticalSection(&cs2);
LeaveCriticalSection(&cs1);
}

return 1;
}

DWORD WINAPI Thread2(LPVOID lpParameter)
{
for (int i = 0; i < 5; i++)
{
EnterCriticalSection(&cs1);
Sleep(500);
EnterCriticalSection(&cs2);

PrintString(_T("Thread2"));

LeaveCriticalSection(&cs2);
LeaveCriticalSection(&cs1);
}

return 1;
}
作者:segen_jaa