added ability to wait on condition variable for the specified amount of time.

This commit is contained in:
rachytski 2013-01-08 20:48:04 +03:00 committed by Alex Zolotarev
parent f9523d9e39
commit 7a942ac0fd
4 changed files with 30 additions and 8 deletions

View file

@ -21,9 +21,9 @@ namespace threads
m_Condition.Unlock();
}
void ConditionGuard::Wait()
void ConditionGuard::Wait(unsigned ms)
{
m_Condition.Wait();
m_Condition.Wait(ms);
}
void ConditionGuard::Signal(bool broadcast)

View file

@ -20,7 +20,7 @@ namespace threads
~Condition();
void Signal(bool broadcast = false);
void Wait();
void Wait(unsigned ms = -1);
void Lock();
void Unlock();
};
@ -33,7 +33,7 @@ namespace threads
public:
ConditionGuard(Condition & condition);
~ConditionGuard();
void Wait();
void Wait(unsigned ms = -1);
void Signal(bool broadcast = false);
};
}

View file

@ -5,6 +5,10 @@
#include "condition.hpp"
#include "mutex.hpp"
#include "../std/stdint.hpp"
#include <sys/time.h>
#include <sys/errno.h>
#include <pthread.h>
namespace threads
@ -38,9 +42,24 @@ namespace threads
::pthread_cond_signal(&m_pImpl->m_Condition);
}
void Condition::Wait()
void Condition::Wait(unsigned ms)
{
::pthread_cond_wait(&m_pImpl->m_Condition, &m_pImpl->m_Mutex.m_Mutex);
if (ms == -1)
::pthread_cond_wait(&m_pImpl->m_Condition, &m_pImpl->m_Mutex.m_Mutex);
else
{
::timeval curtv;
::gettimeofday(&curtv, 0);
::timespec ts;
uint64_t deltaNanoSec = curtv.tv_usec * 1000 + ms * 1000000;
ts.tv_sec = curtv.tv_sec + deltaNanoSec / 1000000000;
ts.tv_nsec = deltaNanoSec % 1000000000;
::pthread_cond_timedwait(&m_pImpl->m_Condition, &m_pImpl->m_Mutex.m_Mutex, &ts);
}
}
void Condition::Lock()

View file

@ -53,6 +53,7 @@ namespace threads
void Wait()
{
/// TODO: Use MS parameter.
m_pSleep(&m_Condition, &m_mutex.m_Mutex, INFINITE);
}
@ -159,6 +160,8 @@ namespace threads
void Wait()
{
// TODO : Use MS parameter.
// Avoid race conditions
::EnterCriticalSection(&waiters_count_lock_);
++waiters_count_;
@ -228,9 +231,9 @@ namespace threads
m_pImpl->Signal(broadcast);
}
void Condition::Wait()
void Condition::Wait(unsigned ms)
{
m_pImpl->Wait();
m_pImpl->Wait(ms);
}
void Condition::Lock()