/* *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 hMutex; 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 2nd param is about the current thread is owned, if true,the owner is who call the thread; or no any; */ hMutex = CreateMutex( NULL, false, NULL ); if( !hMutex ) { 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( hMutex ); 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( hMutex ,INFINITE ); EnterCriticalSection(&g_cs); while (!g_isSellOut) { ticket.Sell(); } /* *ReleaseMutex:let other threads goes on */ ReleaseMutex(hMutex); LeaveCriticalSection(&g_cs); return 0; } DWORD WINAPI Thread2Proc(LPVOID lpParameter) { WaitForSingleObject( hMutex ,INFINITE ); EnterCriticalSection(&g_cs); while (!g_isSellOut) { ticket.Sell(); } ReleaseMutex(hMutex); LeaveCriticalSection(&g_cs); return 0; }
多线程Mutex'sExample
最新推荐文章于 2022-10-31 16:10:21 发布