AutoResetEvent.h
// AutoResetEvent.h
//
// Author David Barrett-Lennard
// (C)opyright Cedanet Pty Ltd 2013
#pragma once
#ifndef Ceda_cxMessage_AutoResetEvent_H
#define Ceda_cxMessage_AutoResetEvent_H
#include "cxMessage.h"
#include "Ceda/cxUtils/CedaAssert.h"
#include <mutex>
#include <condition_variable>
namespace ceda
{
class AutoResetEvent
{
cxNotCloneable(AutoResetEvent)
public:
explicit AutoResetEvent(bool signaled = false) : signaled_(signaled) {}
void Signal()
{
std::lock_guard<std::mutex> lock(mutex_);
signaled_ = true;
cv_.notify_one();
}
void Reset()
{
std::lock_guard<std::mutex> lock(mutex_);
signaled_ = false;
}
void Wait()
{
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock,[this]{return signaled_;});
signaled_ = false; // auto reset
}
// Wait with a timeout.
// Returns true if the wait was completed successfully because the event had been signalled
bool Wait(uint32 msec)
{
std::unique_lock<std::mutex> lock(mutex_);
if (cv_.wait_for(lock,std::chrono::milliseconds(msec),[this]{return signaled_;}))
{
cxAssert(signaled_);
signaled_ = false; // auto reset
return true;
}
else
{
cxAssert(!signaled_);
return false;
}
}
private:
bool signaled_;
std::mutex mutex_;
std::condition_variable cv_;
};
} // namespace ceda
#endif // include guard