15,471
社区成员
发帖
与我相关
我的任务
分享
#include<windows.h>
#include<iostream.h>
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,NULL);
Sleep(4000);
}