http://topic.csdn.net/u/20090110/13/24689e91-a473-4e9c-8a65-932227f1c44b.html?seed=1495116614
错误代码网址。
修改后的。
DWORD WINAPI ThreadProc_1(LPVOID lpParameter);
DWORD WINAPI ThreadProc_2(LPVOID lpParameter);
int tickets = 100;
HANDLE hMutex;
int main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1 = CreateThread(NULL,0,ThreadProc_1,NULL,0,NULL);
hThread2 = CreateThread(NULL,0,ThreadProc_2,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
hMutex = CreateMutex(NULL,FALSE,NULL);
Sleep(4000);
return 0;
}
DWORD WINAPI ThreadProc_1(LPVOID lpParameter)
{
DWORD result1;
while(TRUE)
{
result1 = WaitForSingleObject(hMutex,INFINITE);
if(tickets && result1 == WAIT_OBJECT_0)
{
cout <<"Thread1 sells ticket:" <<tickets-- <<endl;
}
else
{
break;
}
ReleaseMutex(hMutex);
}
return 0;
}
DWORD WINAPI ThreadProc_2(LPVOID lpParameter)
{
DWORD result2;
while(TRUE)
{
result2 = WaitForSingleObject(hMutex,INFINITE);
if(tickets && result2 == WAIT_OBJECT_0)
{
cout <<"Thread2 sells ticket:" <<tickets-- <<endl;
}
else
{
break;
}
ReleaseMutex(hMutex);
}
return 0;
}