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

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

* lock.h

* Copyright (C) | 2006-11-9 | by denny <[email protected]>

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

#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 <[email protected]>

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

#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;

}

 

你可能感兴趣的:(跨平台开发连载(3_同步互斥锁))