diff --git a/include/Common.hpp b/include/Common.hpp index aaa28df..621c5f5 100644 --- a/include/Common.hpp +++ b/include/Common.hpp @@ -4,5 +4,6 @@ #define TRACE(x) std::cout << x << " " << __PRETTY_FUNCTION__ << \ " @ " << __FILE__ << " : " << __LINE__ << std::endl #else + /// @todo Get rid of the "warning: statement has no effect" compiler msgs #define TRACE(x) "" #endif \ No newline at end of file diff --git a/include/ConditionVariable.hpp b/include/ConditionVariable.hpp new file mode 100644 index 0000000..6161094 --- /dev/null +++ b/include/ConditionVariable.hpp @@ -0,0 +1,29 @@ +#ifndef CONDITION_VARIABLE_HPP +#define CONDITION_VARIABLE_HPP + +#include "Mutex.hpp" +#include // pthread_cond + +class ConditionVariable +{ + +public: + + ConditionVariable(Mutex* m); + ~ConditionVariable(); + + void wait(const int interval = 0); + void signal(); + void broadcast(); + +private: + + ConditionVariable(const ConditionVariable&); + ConditionVariable& operator=(const ConditionVariable&); + + Mutex* m_mutex; + pthread_cond_t m_condVar; + +}; + +#endif // CONDITION_VARIABLE_HPP diff --git a/include/Mutex.hpp b/include/Mutex.hpp index 6f35603..8ceff2c 100644 --- a/include/Mutex.hpp +++ b/include/Mutex.hpp @@ -14,6 +14,7 @@ public: void lock(); void unlock(); bool tryLock(int interval = 0); + pthread_mutex_t* getPThreadMutex(); private: diff --git a/src/ConditionVariable.cpp b/src/ConditionVariable.cpp new file mode 100644 index 0000000..d3f7a7c --- /dev/null +++ b/src/ConditionVariable.cpp @@ -0,0 +1,49 @@ +#include "ConditionVariable.hpp" +#include "Common.hpp" + +#include + +ConditionVariable::ConditionVariable(Mutex* m) + : m_mutex(m) + , m_condVar(PTHREAD_COND_INITIALIZER) +{ + TRACE(this); + pthread_cond_init( &m_condVar, 0 ); +} + + +ConditionVariable::~ConditionVariable() +{ + TRACE(this); + pthread_cond_destroy( &m_condVar ); +} + + +void ConditionVariable::wait(const int interval) +{ + TRACE(this); + if ( interval == 0 ) { + pthread_cond_wait( &m_condVar, m_mutex->getPThreadMutex() ); + } else { + timespec abs_time; + clock_gettime ( CLOCK_REALTIME, &abs_time ); + abs_time.tv_nsec += interval * 1000000; + if ( abs_time.tv_nsec >= 1000000000 ) { + abs_time.tv_nsec -= 1000000000; + abs_time.tv_sec += 1; + } + pthread_cond_timedwait( &m_condVar, m_mutex->getPThreadMutex(), &abs_time ); + } +} + +void ConditionVariable::signal() +{ + TRACE(this); + pthread_cond_signal( &m_condVar ); +} + +void ConditionVariable::broadcast() +{ + TRACE(this); + pthread_cond_broadcast( &m_condVar ); +} diff --git a/src/Mutex.cpp b/src/Mutex.cpp index f975cde..ef81f66 100644 --- a/src/Mutex.cpp +++ b/src/Mutex.cpp @@ -64,3 +64,8 @@ bool Mutex::tryLock(int interval) } } + +pthread_mutex_t* Mutex::getPThreadMutex() +{ + return &m_mutex; +}