Search This Blog

Saturday, June 11, 2005

Conditions - POSIX Implementation

As with the mutex class, the POSIX version of the condition is trivial, due to the native support by the OS. The POSIX APIs allow you to specify a mutex to use each time you wait on the condition. However, as I can't see any use for this, and it leaves more room for error, I've decided to bind the condition to its mutex on construction. The code:

class CCondition
{
private:
CMutex &m_pairedMutex; // Paired mutex
pthread_cond_t m_cond; // Condition variable

public:
inline CCondition(CMutex &mutex) : m_pairedMutex(mutex)
{
if (pthread_cond_init(&m_cond, NULL) != 0)
throw std::bad_alloc("Unable to create condition");
}

inline ~CCondition()
{
verify(pthread_cond_destroy(&m_cond) == 0);
}

inline void Signal(bool bSignalAll = false)
{
int nRetVal;
if (bSignalAll)
nRetVal = pthread_cond_broadcast(&m_cond); // Signal all
else
nRetVal = pthread_cond_signal(&m_cond); // Signal one

assert(nRetVal == 0);
}

inline void Wait()
{
verify(pthread_cond_wait(&m_cond, &m_pairedMutex.GetMutex()) == 0);
}
};

No comments: