15,472
社区成员
发帖
与我相关
我的任务
分享
if(tickets>0)
{
Sleep(1);
cout<<"thread2 sell ticket : "<<tickets--<<endl;
}
else
{
ReleaseMutex(hMutex);
break;
}
#include <windows.h>
#include <iostream>
using namespace std;
DWORD WINAPI Fun1Proc(
LPVOID lpParameter // thread data
);
int index=0;
int tickets=100;
HANDLE hMutex;
void main()
{
hMutex=CreateMutex(NULL,FALSE,NULL);
if(hMutex)
{
if(ERROR_ALREADY_EXISTS==GetLastError())
{
cout<<"only one instance can run!"<<endl;
return;
}
}
HANDLE hThread1;
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
CloseHandle(hThread1);
while(TRUE)
{
int a=WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
Sleep(1);
cout<<"thread2 sell ticket : "<<tickets--<<endl;
}
else
{
ReleaseMutex(hMutex);
break;
}
ReleaseMutex(hMutex);
}
cout<<"thread2 is running"<<endl;
Sleep(4000);
}
DWORD WINAPI Fun1Proc(
LPVOID lpParameter // thread data
)
{
while(TRUE)
{
int a=WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
Sleep(1);
cout<<"thread1 sell ticket : "<<tickets--<<endl;
}
else
{
ReleaseMutex(hMutex);
break;
}
ReleaseMutex(hMutex);
}
return 0;
}