#include <Windows.h>
#include <iostream>
using namespace std;
DWORD WINAPI Fun1(LPVOID lpParameter);
DWORD WINAPI Fun2(LPVOID lpParameter);
int index = 0;
int tickets = 100;
HANDLE hMutex;
int main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1 = CreateThread(NULL,0,Fun1,NULL,0,NULL);
hThread2 = CreateThread(NULL,0,Fun2,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
hMutex=CreateMutex(NULL, FALSE, "tickets");//申請一個名爲tickets的互斥資源且不屬於當前線程
//WaitForSingleObject(hMutex, INFINITE);
//ReleaseMutex(hMutex);
//或
/* hMutex=CreateMutex(NULL, TRUE, "tickets");<span style="font-family: Arial, Helvetica, sans-serif;">//申請一個名爲tickets的互斥資源且屬於當前線程,要釋放後該互斥資源,其他線程才能用</span>
WaitForSingleObject(hMutex, INFINITE);
ReleaseMutex(hMutex);
ReleaseMutex(hMutex); */
Sleep(400000); //主線程掛起400秒,先去執行子線程
return 0;
}
DWORD WINAPI Fun1(LPVOID lpParameter)
{
while (TRUE)
{
ReleaseMutex(hMutex);
WaitForSingleObject(hMutex, INFINITE);
if (tickets > 0)
{
Sleep(1000);
cout<<"thread1 sell ticket : "<<tickets--<<endl;
}
else
{
break;
}
ReleaseMutex(hMutex);
}
return 0;
}
DWORD WINAPI Fun2(LPVOID lpParameter)
{
while (TRUE)
{
ReleaseMutex(hMutex);
WaitForSingleObject(hMutex, INFINITE);
if (tickets > 0)
{
Sleep(1000);
cout<<"thread2 sell ticket : "<<tickets--<<endl;
}
else
{
break;
}
ReleaseMutex(hMutex);
}
return 0;
}