跨平台开发连载(3_同步互斥锁)

/**********************************************************

* lock.h

* Copyright (C) | 2006-11-9 | by denny <wqf363@hotmail.com>

**********************************************************/

#ifndef LOCK_H

#define LOCK_H

 

#include <pthread.h>

 

class  CLockableObject

{

public:

       CLockableObject(){}

       ~CLockableObject(){}

 

       virtual void Lock() = 0;

       virtual void Unlock() = 0;

};

 

class CMyMutex: public CLockableObject

{

public:

       CMyMutex();

       ~CMyMutex();

 

       void Lock();

       void Unlock();

private:

#ifndef WIN32

       pthread_mutex_t  m_tMutex;

#else

       CRITICAL_SECTION  m_CriticalSection;

#endif

};

 

 

class CLock

{

public:

       CLock(CLockableObject *pLockableObject)

       {

       m_pLockableObject = pLockableObject;

       m_pLockableObject->Lock();

       }

       ~CLock()

       {

              m_pLockableObject->Unlock();

       }

private:

       CLockableObject *m_pLockableObject;

};

#endif

 

/**********************************************************

* lock.cpp

* Copyright (C) | 2006-11-9 | by denny <wqf363@hotmail.com>

**********************************************************/

#include "Lock.h"

 

CMyMutex::CMyMutex()

{

#ifndef WIN32

       pthread_mutex_init(&m_tMutex, NULL);

#else

       InitializeCriticalSection(&m_CriticalSection);

#endif

}

 

CMyMutex::~CMyMutex()

{

#ifndef WIN32

       int iResult = pthread_mutex_destroy(&m_tMutex);

       if (iResult)

              std::cout<<"pthread_mutex_destroy error"<<std::endl;                                   

#else

       DeleteCriticalSection(&m_CriticalSection);

#endif

}

 

bool CMyMutex::Lock()

{

#ifndef WIN32

       int iResult = pthread_mutex_lock(&m_tMutex);

       if (iResult)

              std::cout<<"pthread_mutex_lock error"<<std::endl;                                       

#else

       EnterCriticalSection(&m_CriticalSection);

#endif

       return true;

}

 

bool CMyMutex::TryLock()

{

#ifndef WIN32

       int iResult = pthread_mutex_trylock(&m_tMutex);

       if (iResult)

       {

              if (iResult == EBUSY)

                     return false;

              std::cout<<"pthread_mutex_trylock error"<<std::endl;                            

       }                         

#else

       //LeaveCriticalSection(&m_CriticalSection);

#endif

       return true;

}

 

bool CMyMutex::Unlock()

{

#ifndef WIN32

       int iResult = pthread_mutex_unlock(&m_tMutex);

       if (iResult)

              std::cout<<"pthread_mutex_unlock error"<<std::endl;

                           

#else

       LeaveCriticalSection(&m_CriticalSection);

#endif

       return true;

}

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值