多线程Event的使用例子
来源:互联网 发布:linux怎么udp端口测试 编辑:程序博客网 时间:2024/06/06 02:33
#include <windows.h> #include <iostream>#include <stdexcept>/**Date:31/oct/2013*Author:pjgan*Complier:VC++2008*Theme: Study the Thread,the example is to sell the tickets;*/CRITICAL_SECTION g_cs;bool g_isSellOut = false;HANDLE hEvent; DWORD WINAPI Thread1Proc(LPVOID lpParameter); DWORD WINAPI Thread2Proc(LPVOID lpParameter);class Ticket{public: Ticket(); void Sell(); ~Ticket();private: int ticketnum; };Ticket::Ticket():ticketnum(100){ InitializeCriticalSection(&g_cs); /* *Param: the 3th Param ,is setted triggered if set true */ hEvent = CreateEvent( NULL, false, true, NULL ); if( !hEvent ) { throw std::runtime_error("Build Event failed!"); }}void Ticket::Sell(){ if( ticketnum > 0 ) { std::cout<<"Ticket left "<< ticketnum-- <<std::endl; } else { std::cout<<"All ticket has sold out!"<<std::endl; g_isSellOut = true; } }Ticket::~Ticket(){ CloseHandle( hEvent ); DeleteCriticalSection(&g_cs);}Ticket ticket;int main() { HANDLE hThread1=CreateThread( NULL, 0, Thread1Proc, 0, 0, NULL ); HANDLE hThread2=CreateThread( NULL, 0, Thread2Proc, 0, 0, NULL ); WaitForSingleObject( hThread1, INFINITE ); WaitForSingleObject( hThread2, INFINITE ); CloseHandle(hThread1); CloseHandle(hThread2); return 0;} DWORD WINAPI Thread1Proc(LPVOID lpParameter) { /* *waitforsinglobject:wait for the hEvent is triggered; */ WaitForSingleObject( hEvent ,INFINITE ); /* *SetEvent:set the thread triggered by the handle of the thread; */ SetEvent( hEvent ); EnterCriticalSection(&g_cs); while (!g_isSellOut) { ticket.Sell(); } LeaveCriticalSection(&g_cs); return 0; } DWORD WINAPI Thread2Proc(LPVOID lpParameter) { WaitForSingleObject( hEvent ,INFINITE ); SetEvent( hEvent ); EnterCriticalSection(&g_cs); while (!g_isSellOut) { ticket.Sell(); } LeaveCriticalSection(&g_cs); return 0; }