#include "stdafx.h"
#include <windows.h> #include "iostream"using namespace std;
int tickets = 100; CRITICAL_SECTION g_cs; DWORD WINAPI func1(LPVOID lpParameter) { while(true) { EnterCriticalSection(&g_cs); if(tickets>0) { Sleep(1); cout<<"Thread1 sells tickets"<<tickets--<<endl; } else break; LeaveCriticalSection(&g_cs); } return 0; }DWORD WINAPI func2(LPVOID lpParameter)
{ while(true) { EnterCriticalSection(&g_cs); if(tickets>0) { Sleep(1); cout<<"Thread2 sells tickets"<<tickets--<<endl; } else { break; } LeaveCriticalSection(&g_cs); } return 0; } int _tmain(int argc, _TCHAR* argv[]) { HANDLE hThread1 = CreateThread(NULL,0,func1,NULL,0,NULL); HANDLE hThread2 = CreateThread(NULL,0,func2,NULL,0,NULL); CloseHandle(hThread1); CloseHandle(hThread2); InitializeCriticalSection(&g_cs); Sleep(4000); DeleteCriticalSection(&g_cs); return 0; }