IBR-DTNSuite
0.8
|
00001 #include "ibrcommon/config.h" 00002 #include "ibrcommon/thread/Mutex.h" 00003 #include <errno.h> 00004 00005 namespace ibrcommon 00006 { 00007 MutexInterface::~MutexInterface() 00008 { 00009 }; 00010 00011 Mutex::Mutex(MUTEX_TYPE type) 00012 { 00013 pthread_mutexattr_init(&m_attr); 00014 pthread_mutexattr_settype(&m_attr, type); 00015 pthread_mutex_init(&m_mutex, &m_attr); 00016 } 00017 00018 Mutex::~Mutex() 00019 { 00020 pthread_mutex_destroy( &m_mutex ); 00021 pthread_mutexattr_destroy(&m_attr); 00022 } 00023 00024 void Mutex::trylock() throw (MutexException) 00025 { 00026 int ret = pthread_mutex_trylock( &m_mutex ); 00027 00028 switch (ret) 00029 { 00030 case 0: 00031 break; 00032 00033 case EBUSY: 00034 throw MutexException("The mutex could not be acquired because it was already locked."); 00035 break; 00036 } 00037 } 00038 00039 void Mutex::enter() throw (MutexException) 00040 { 00041 switch (pthread_mutex_lock( &m_mutex )) 00042 { 00043 case 0: 00044 return; 00045 00046 // case EINVAL: 00047 // throw MutexException("The mutex was created with the protocol attribute having the value PTHREAD_PRIO_PROTECT and the calling thread's priority is higher than the mutex's current priority ceiling."); 00048 00049 // The pthread_mutex_trylock() function will fail if: 00050 00051 case EBUSY: 00052 throw MutexException("The mutex could not be acquired because it was already locked."); 00053 00054 // The pthread_mutex_lock(), pthread_mutex_trylock() and pthread_mutex_unlock() functions may fail if: 00055 00056 case EINVAL: 00057 throw MutexException("The value specified by mutex does not refer to an initialised mutex object."); 00058 00059 case EAGAIN: 00060 throw MutexException("The mutex could not be acquired because the maximum number of recursive locks for mutex has been exceeded."); 00061 00062 // The pthread_mutex_lock() function may fail if: 00063 00064 case EDEADLK: 00065 throw MutexException("The current thread already owns the mutex."); 00066 00067 // The pthread_mutex_unlock() function may fail if: 00068 00069 case EPERM: 00070 throw MutexException("The current thread does not own the mutex."); 00071 00072 default: 00073 throw MutexException("can not lock the mutex"); 00074 } 00075 } 00076 00077 void Mutex::leave() throw (MutexException) 00078 { 00079 if (0 != pthread_mutex_unlock( &m_mutex )) 00080 { 00081 throw MutexException("can not unlock mutex"); 00082 } 00083 } 00084 00085 MutexMock Mutex::_dummy; 00086 00087 MutexInterface& Mutex::dummy() 00088 { 00089 return _dummy; 00090 }; 00091 }