Search This Blog

Friday, June 10, 2005

Mutexes - POSIX Implementation

Really there isn't much to say, here. The POSIX version of our mutex is nothing more than a thin wrapper around a pthread_mutex, with profuse use of our verify macro.

class CCondition; // Circular reference incoming. We don't have any choice but to forward declare it.

class CMutex // POSIX version of CMutex: pthread_mutex (fast?)
{
private:
pthread_mutex_t m_mutex;

inline pthread_mutex_t &GetMutex()
{
return m_mutex;
}

public:
// Compatible prototype, even though the spin count is unused
inline CMutex(unsigned int nSpinCount = 0)
{
if (pthread_mutex_init(&m_mutex) != 0)
throw bad_alloc("Unable to create mutex");
}
inline ~CMutex()
{ verify(pthread_mutex_destroy(&m_mutex) == 0); }

inline bool TryEnter()
{ return (pthread_mutex_trylock(&m_mutex) == 0); }
inline void Enter()
{ verify(pthread_mutex_lock(&m_mutex) == 0); }
inline void Leave()
{ verify(pthread_mutex_unlock(&m_mutex) == 0); }

// Allow CCondition to access the mutex directly
friend class CCondition;
};

No comments: