1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
#include "CMutex.h" #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #define DEBUG_ERROR(format,...) do{ printf(""format", FileName:%s, FuncName:%s, LineNum:%d\n",\ ##__VA_ARGS__, __FILE__, __func__, __LINE__);}while(0)
CMutex::CMutex(bool IsRecursive) { m_pMutex = new pthread_mutex_t; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); int nResult = 0; do{ if (IsRecursive) { nResult = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); nResult = 20; if ( 0 != nResult ) { DEBUG_ERROR("pthread_mutexattr_settype() failed:%s", strerror(nResult)); break; } } else { nResult = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL); if ( 0 != nResult ) { DEBUG_ERROR("pthread_mutexattr_settype() failed:%s", strerror(nResult)); break; } }
nResult = pthread_mutex_init(m_pMutex, &attr); if( 0 != nResult ) { DEBUG_ERROR("pthread_mutexattr_settype() failed:%s", strerror(nResult)); break; } }while(0); }
CMutex::~CMutex() { int nResult = pthread_mutex_destroy(m_pMutex); if( nResult != 0 ) { DEBUG_ERROR("CMutex ~CMutex() pthread_mutex_destroy() failed:%s", strerror(nResult)); } if ( m_pMutex != NULL ) delete m_pMutex; }
bool CMutex::Lock() { int nResult = pthread_mutex_lock(m_pMutex); if( nResult < 0 ) { DEBUG_ERROR("CMutex lock() pthread_mutex_lock() failed:%s", strerror(nResult)); return false; } return true; }
bool CMutex::UnLock() { int nResult = pthread_mutex_unlock(m_pMutex); if ( nResult < 0 ) { DEBUG_ERROR("CMutex unlock() pthread_mutex_unlock() failed:%s", strerror(nResult)); return false; } return true; }
bool CMutex::TryLock() { int nResult = pthread_mutex_trylock(m_pMutex); if ( nResult != 0 ) { DEBUG_ERROR("CMutex trylock() pthread_mutex_trylock() failed:%s", strerror(nResult)); return false; } return true; }
|