#include < windows.h > #include < iostream > using namespace std;DWORD WINAPI Fun1Proc(LPVOID lpParameter);DWORD WINAPI Fun2Proc(LPVOID lpParameter); int tickets = 100 ;HANDLE g_hEvent;void main(){ HANDLE hThread1; HANDLE hThread2; //************************************************** // 创建一个命名的自动重置事件内核对象 g_hEvent = CreateEvent( NULL , FALSE , FALSE ,LPCWSTR( " tickets " )); if (g_hEvent) { if (ERROR_ALREADY_EXISTS == GetLastError()) { cout << " only one instance can run! " << endl; return; } } //************************************************** SetEvent(g_hEvent); // 创建线程 hThread1 = CreateThread( NULL , 0 ,Fun1Proc, NULL , 0 , NULL ); hThread2 = CreateThread( NULL , 0 ,Fun2Proc, NULL , 0 , NULL ); Sleep( 40000 ); // 关闭事件对象句柄 CloseHandle(g_hEvent);}DWORD WINAPI Fun1Proc(LPVOID lpParameter){ while ( TRUE ) { WaitForSingleObject(g_hEvent,INFINITE); // ResetEvent(g_hEvent); if (tickets > 0 ) { Sleep( 1 ); cout << " thread1 sell ticket : " << tickets --<< endl; SetEvent(g_hEvent); } else { SetEvent(g_hEvent); break; } } return 0 ;}DWORD WINAPI Fun2Proc(LPVOID lpParameter){ while ( TRUE ) { WaitForSingleObject(g_hEvent,INFINITE); // ResetEvent(g_hEvent); if (tickets > 0 ) { cout << " Thread2 sell ticket : " << tickets --<< endl; SetEvent(g_hEvent); } else { SetEvent(g_hEvent); break; } } return 0 ;}