多线程Mutex'sExample

/*
*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; 
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值