5 #include <condition_variable> 26 std::unique_lock<std::mutex> lock(
m_mtx);
33 std::unique_lock<std::mutex> lock(
m_mtx);
38 template <
class Clock,
class Duration>
39 bool waitUntil(
const std::chrono::time_point<Clock, Duration>& point)
41 std::unique_lock<std::mutex> lock(
m_mtx);
42 if (!
m_cv.wait_until(lock, point, [
this]() { return m_count > 0; }))
50 std::condition_variable
m_cv;
70 m_th = std::thread([
this] { run(); });
77 add(std::chrono::milliseconds(0), [
this](
bool) { m_finish =
true; });
85 uint64_t
add(std::chrono::milliseconds milliseconds, std::function<
void(
bool)> handler)
88 item.
end = Clock::now() + milliseconds;
89 item.
handler = std::move(handler);
91 std::unique_lock<std::mutex> lk(
m_mtx);
92 uint64_t
id = ++m_idcounter;
94 m_items.push(std::move(item));
114 std::unique_lock<std::mutex> lk(
m_mtx);
115 for (
auto&& item : m_items.getContainer())
117 if (item.id ==
id && item.handler)
121 newItem.
end = Clock::time_point();
128 newItem.
handler = std::move(item.handler);
129 item.handler =
nullptr;
130 m_items.push(std::move(newItem));
134 m_checkWork.notify();
148 std::unique_lock<std::mutex> lk(
m_mtx);
149 for (
auto&& item : m_items.getContainer())
153 item.end = Clock::time_point();
157 auto ret = m_items.size();
160 m_checkWork.notify();
165 using Clock = std::chrono::steady_clock;
173 auto end = calcWaitTime();
178 m_checkWork.waitUntil(end.second);
193 assert(m_items.size() == 0);
198 std::lock_guard<std::mutex> lk(
m_mtx);
199 while (m_items.size())
201 if (m_items.top().handler)
204 return std::make_pair(
true, m_items.top().end);
215 return std::make_pair(
false, Clock::time_point());
220 std::unique_lock<std::mutex> lk(
m_mtx);
221 while (m_items.size() && m_items.top().end <= Clock::now())
223 WorkItem item(std::move(m_items.top()));
235 bool m_finish =
false;
236 uint64_t m_idcounter = 0;
245 return end > other.
end;
252 :
public std::priority_queue<WorkItem, std::vector<WorkItem>, std::greater<WorkItem>>
263 #endif // TIMERQUEUE_H
size_t cancelAll()
Cancels all timers.
std::condition_variable m_cv
bool waitUntil(const std::chrono::time_point< Clock, Duration > &point)
static pthread_mutex_t mutex
Semaphore(unsigned int count=0)
std::function< void(bool)> handler
uint64_t add(std::chrono::milliseconds milliseconds, std::function< void(bool)> handler)
Adds a new timer.
std::chrono::steady_clock Clock
details::Semaphore m_checkWork
static volatile int count
std::pair< bool, Clock::time_point > calcWaitTime()
std::vector< WorkItem > & getContainer()
bool operator>(const WorkItem &other) const
size_t cancel(uint64_t id)
Cancels the specified timer.