多线程Mutex'sExample
来源:互联网 发布:网络维护服务外包请示 编辑:程序博客网 时间:2024/05/22 13:12
/**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; }