Add Common::Event::WaitFor(), which has the same semantics as std::condition_variable::wait_for() (with millisecond units).

This commit is contained in:
Shawn Hoffman 2014-08-12 22:53:17 -07:00
parent 375be67158
commit 87c324c55a
1 changed files with 40 additions and 3 deletions

View File

@ -16,6 +16,7 @@
#include <concrt.h> #include <concrt.h>
#endif #endif
#include <chrono>
#include <condition_variable> #include <condition_variable>
#include <mutex> #include <mutex>
@ -48,6 +49,20 @@ public:
m_flag.Clear(); m_flag.Clear();
} }
template<class Rep, class Period>
bool WaitFor(const std::chrono::duration<Rep, Period>& rel_time)
{
if (m_flag.TestAndClear())
return true;
std::unique_lock<std::mutex> lk(m_mutex);
bool signaled = m_condvar.wait_for(lk, rel_time,
[&]{ return m_flag.IsSet(); });
m_flag.Clear();
return signaled;
}
void Reset() void Reset()
{ {
// no other action required, since wait loops on // no other action required, since wait loops on
@ -65,9 +80,31 @@ private:
class Event final class Event final
{ {
public: public:
void Set() { m_event.set(); } void Set()
void Wait() { m_event.wait(); m_event.reset(); } {
void Reset() { m_event.reset(); } m_event.set();
}
void Wait()
{
m_event.wait();
m_event.reset();
}
template<class Rep, class Period>
bool WaitFor(const std::chrono::duration<Rep, Period>& rel_time)
{
bool signaled = m_event.wait(
(u32)std::chrono::duration_cast<std::chrono::milliseconds>(rel_time).count()
) == 0;
m_event.reset();
return signaled;
}
void Reset()
{
m_event.reset();
}
private: private:
concurrency::event m_event; concurrency::event m_event;