4 #include <condition_variable> 25 std::unique_lock<std::mutex> lock(
m_mtx);
32 std::unique_lock<std::mutex> lock(
m_mtx);
37 template <
class Clock,
class Duration>
38 bool waitUntil(
const std::chrono::time_point<Clock, Duration>& point)
40 std::unique_lock<std::mutex> lock(
m_mtx);
41 if (!
m_cv.wait_until(lock, point, [
this]() { return m_count > 0; }))
49 std::condition_variable
m_cv;
64 template <
typename _Clock = std::chrono::steady_clock,
65 typename _Duration = std::chrono::steady_clock::duration>
71 m_th = std::thread([
this] { run(); });
78 add(std::chrono::milliseconds(0), [
this](
bool) { m_finish =
true; });
86 uint64_t
add(std::chrono::milliseconds milliseconds, std::function<
void(
bool)> handler)
89 item.
end = _Clock::now() + milliseconds;
90 item.
handler = std::move(handler);
92 std::unique_lock<std::mutex> lk(
m_mtx);
93 uint64_t
id = ++m_idcounter;
95 m_items.push(std::move(item));
115 std::unique_lock<std::mutex> lk(
m_mtx);
116 for (
auto&& item : m_items.getContainer())
118 if (item.id ==
id && item.handler)
122 newItem.
end = std::chrono::time_point<_Clock, _Duration>();
129 newItem.
handler = std::move(item.handler);
130 item.handler =
nullptr;
131 m_items.push(std::move(newItem));
135 m_checkWork.notify();
149 std::unique_lock<std::mutex> lk(
m_mtx);
150 for (
auto&& item : m_items.getContainer())
154 item.end = std::chrono::time_point<_Clock, _Duration>();
158 auto ret = m_items.size();
161 m_checkWork.notify();
173 auto end = calcWaitTime();
178 m_checkWork.waitUntil(end.second);
193 assert(m_items.size() == 0);
196 std::pair<bool, std::chrono::time_point<_Clock, _Duration>>
calcWaitTime()
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, std::chrono::time_point<_Clock, _Duration>());
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;
240 std::chrono::time_point<_Clock, _Duration>
end;
245 return end > other.
end;
252 :
public std::priority_queue<WorkItem, std::vector<WorkItem>, std::greater<WorkItem>>
std::condition_variable m_cv
bool operator>(const WorkItem &other) const
std::function< void(bool)> handler
bool waitUntil(const std::chrono::time_point< Clock, Duration > &point)
details::Semaphore m_checkWork
size_t cancel(uint64_t id)
Cancels the specified timer.
static pthread_mutex_t mutex
std::vector< WorkItem > & getContainer()
Semaphore(unsigned int count=0)
std::chrono::time_point< _Clock, _Duration > end
size_t cancelAll()
Cancels all timers.
static volatile int count
uint64_t add(std::chrono::milliseconds milliseconds, std::function< void(bool)> handler)
Adds a new timer.
std::pair< bool, std::chrono::time_point< _Clock, _Duration > > calcWaitTime()