16,548
社区成员




//加这一行Sleep到 Fun1Proc的同步体以外:
Sleep(10); // <-------add this line
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
Sleep(1);
cout < <"thread1 sell tickets : " < <tickets-- < <endl;
}
else
{
break;
}
ReleaseMutex(hMutex);
#include <windows.h>
#include <iostream>
using namespace std;
int tickets=100;
HANDLE hSold;
HANDLE hProduced;
DWORD WINAPI FunProc( LPVOID lpParameter )
{
BOOL isSeller = (BOOL)lpParameter;
HANDLE hPrerequisite = isSeller ? hSold : hProduced;
HANDLE hSignaling = isSeller ? hProduced : hSold;
while(TRUE)
{
WaitForSingleObject(hPrerequisite,INFINITE);
if(tickets>0)
{
cout << "thread" << (isSeller ? "1 sell":"2 buy ") << " tickets : " << tickets-- << endl;
}
else
{
break;
}
SetEvent(hSignaling);
}
return 0;
}
void main()
{
hSold = CreateEvent(NULL, FALSE, TRUE, NULL);
hProduced = CreateEvent(NULL, FALSE, FALSE, NULL);
CloseHandle(CreateThread(NULL,0,FunProc,(LPVOID)TRUE ,0,0));
CloseHandle(CreateThread(NULL,0,FunProc,(LPVOID)FALSE,0,0));
getchar();
}