Small Mutex refactor

master
Denes Matetelki 12 years ago
parent d64f8bdf75
commit 1b94865540

@ -8,38 +8,36 @@ class Mutex
public: public:
Mutex(int kind = PTHREAD_MUTEX_DEFAULT); enum MutexType {
Normal = PTHREAD_MUTEX_NORMAL, // no deadlock check, unlock a non-locked mutex results undefined behaviour
ErrorCheck = PTHREAD_MUTEX_ERRORCHECK, // error returned when relock or unlocking a non-locked mutex
Recursive = PTHREAD_MUTEX_RECURSIVE, // Lock counting with error handling.
Default = PTHREAD_MUTEX_DEFAULT // equals normal
};
Mutex(MutexType type = MutexType::Default);
~Mutex(); ~Mutex();
/** MutexType getType() const { return m_type; }
* Locks mutex. If already locked, the calling thread shall block until pthread_mutex_t* getPThreadMutex() { return &m_mutex; }
* the mutex becomes available.
* @returns If successful, zero; otherwise, an error number. // If already locked, the calling thread shall block until the mutex becomes available.
*/
int lock(); int lock();
/**
*
*/
int unlock(); int unlock();
/** // If currently locked, the call shall return immediately.
* If currently locked, the call shall return immediately.
* @returns Zero if a lock acquired. Otherwise, an error number.
*/
int tryLock( const long int intervalSec = 0, int tryLock( const long int intervalSec = 0,
const long int intervalNSec = 0 ); const long int intervalNSec = 0 );
pthread_mutex_t* getPThreadMutex();
private: private:
Mutex(const Mutex& m); Mutex(const Mutex& m);
Mutex& operator=(const Mutex& m); Mutex& operator=(const Mutex& m);
pthread_mutex_t m_mutex; pthread_mutex_t m_mutex;
MutexType m_type;
pthread_mutexattr_t m_attr;
}; };
#endif // MUTEX_HPP #endif // MUTEX_HPP

@ -4,24 +4,26 @@
#include <time.h> #include <time.h>
namespace {
pthread_mutex_t& MutexCtor( pthread_mutex_t& mutex ) pthread_mutex_t& MutexCtor( pthread_mutex_t& mutex )
{ {
pthread_mutex_init( &mutex, 0 ); pthread_mutex_init( &mutex, 0 );
return mutex; return mutex;
} }
} // anonym namespace
Mutex::Mutex( int kind ) Mutex::Mutex( MutexType type )
: m_mutex( MutexCtor( m_mutex ) ) : m_mutex( MutexCtor( m_mutex ) ) // init with function
, m_type( type )
{ {
TRACE; TRACE;
if ( kind != PTHREAD_MUTEX_DEFAULT ) { if ( type != PTHREAD_MUTEX_DEFAULT ) {
/// @bug passing local variables address pthread_mutexattr_init( &m_attr );
pthread_mutexattr_t attr; pthread_mutexattr_settype( &m_attr, type );
pthread_mutexattr_init( &attr ); pthread_mutex_init( &m_mutex, &m_attr );
pthread_mutexattr_settype( &attr, kind );
pthread_mutex_init( &m_mutex, &attr );
} }
} }
@ -57,9 +59,3 @@ int Mutex::tryLock( const long int intervalSec, const long int intervalNSec )
return pthread_mutex_timedlock( &m_mutex, &tspec ); return pthread_mutex_timedlock( &m_mutex, &tspec );
} }
} }
pthread_mutex_t* Mutex::getPThreadMutex()
{
return &m_mutex;
}

Loading…
Cancel
Save