Signal.h
/**
* desp:
* auth: wk
* date: 2020/01/13
*/
#ifndef __SIGNAL_H__
#define __SIGNAL_H__
#include <mutex>
#include <condition_variable>
class Signal
{
private:
std::mutex lock;
std::condition_variable cond_var;
bool ready;
private:
Signal(const Signal& signal) = delete;
Signal& operator=(const Signal& signal) = delete;
public:
Signal(bool ready = false);
~Signal() = default;
public:
void Notify();
void Wait();
bool WaitFor(uint32_t timeMs);
};
#endif
Signal.cpp
#include "Signal.h"
Signal::Signal(bool ready)
: ready(ready)
{
}
void Signal::Notify()
{
std::unique_lock<std::mutex> lk(lock);
ready = true;
cond_var.notify_one();
}
void Signal::Wait()
{
std::unique_lock<std::mutex> lk(lock);
while (!ready)
{
cond_var.wait(lk);
}
ready = false;
}
bool Signal::WaitFor(uint32_t timeMs)
{
std::unique_lock<std::mutex> lk(lock);
if (!ready)
{
if (cond_var.wait_for(lk, std::chrono::milliseconds(timeMs)) == std::cv_status::timeout)
{
return false;
}
}
ready = false;
return true;
}