#include <windows.h>
#include <iostream>
using namespace std;
DWORD WINAPI MyThreadProc1(LPVOID lpParameter); //thread data
DWORD WINAPI MyThreadProc2(LPVOID lpParameter);
int tickets=100;
CRITICAL_SECTION g_cs;
int main(){
DWORD tid1=0,tid2=0;
HANDLE handle1 = CreateThread(NULL,0,MyThreadProc1,NULL,CREATE_SUSPENDED ,&tid1);
HANDLE handle2 = CreateThread(NULL,0,MyThreadProc2,NULL,CREATE_SUSPENDED ,&tid2);
ResumeThread(handle1);
ResumeThread(handle2);
InitializeCriticalSection(&g_cs);
Sleep(5000);
DeleteCriticalSection(&g_cs);
CloseHandle(handle1);
CloseHandle(handle2);
cout<< "SubThread1 ID:" << hex << uppercase<< tid1 << endl;
cout<< "SubThread2 ID:" << hex << uppercase<< tid2 << endl;
system("pause");
return 0;
}
DWORD WINAPI MyThreadProc1(LPVOID lpParameter )
{
while(TRUE){
EnterCriticalSection(&g_cs);
if(tickets){
cout<<"子线程1卖票:"<<tickets<<endl;
--tickets;
Sleep(15);
LeaveCriticalSection(&g_cs);
}
else
{
LeaveCriticalSection(&g_cs);
break;
}
}
return 1;
}
DWORD WINAPI MyThreadProc2(LPVOID lpParameter)
{
while(TRUE){
EnterCriticalSection(&g_cs);
if(tickets){
cout<<"子线程2卖票:"<<tickets<<endl;
--tickets;
Sleep(15);
LeaveCriticalSection(&g_cs);
}
else
{
LeaveCriticalSection(&g_cs);
break;
}
}
return 1;
}