15,472
社区成员
发帖
与我相关
我的任务
分享
int index=0;
int tickets=100;
HANDLE hMutex;
DWORD WINAPI FunProc1(LPVOID lpParameter)
{
while(1)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
cout<<"Thread1 is telling ticket:"<<tickets--<<endl;
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
DWORD WINAPI FunProc2(LPVOID lpParameter)
{
while(1)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
cout<<"Thread2 is telling ticket:"<<tickets--<<endl;
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
void main()
{
HANDLE hThread1,hThread2;
hThread1=CreateThread(NULL,0,FunProc1,NULL,0,NULL);
hThread2=CreateThread(NULL,0,FunProc2,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
hMutex=CreateMutex(NULL,FALSE,"tickets");
if(hMutex)
{
if(ERROR_ALREADY_EXISTS==GetLastError())
{
cout<<"only one instance can run!"<<endl;
return;
}
}
WaitForSingleObject(hMutex,INFINITE);
ReleaseMutex(hMutex);
ReleaseMutex(hMutex);
Sleep(4000);
}