32 class worker_strategy;
34 class state_t final :
public rpp::details::base_disposable
37 ~state_t()
noexcept override {
dispose(); }
39 template<
typename... Args>
40 void emplace_and_notify(time_point timepoint, Args&&... args)
46 std::lock_guard lock{m_mutex};
47 m_queue.emplace(timepoint, std::forward<Args>(args)...);
52 std::shared_ptr<details::schedulable_base> pop(
bool wait)
56 std::unique_lock lock{m_mutex};
57 m_cv.wait(lock, [&] {
return !wait ||
is_disposed() || !m_queue.is_empty(); });
62 const auto now = worker_strategy::now();
63 if (is_any_ready_schedulable_unsafe(now))
73 const auto top = m_queue.top();
74 m_cv.wait_until(lock, top->get_timepoint(), [&]() { return is_disposed() || m_queue.is_empty() || m_queue.top().get() != top.get() || m_queue.top()->is_disposed() || m_queue.top()->get_timepoint() <= worker_strategy::now(); });
79 bool is_any_ready_schedulable()
81 std::lock_guard lock{m_mutex};
82 return is_any_ready_schedulable_unsafe();
87 std::lock_guard lock{m_mutex};
88 return m_queue.is_empty();
92 bool is_any_ready_schedulable_unsafe(time_point now = worker_strategy::now())
const
94 return !m_queue.is_empty() && (m_queue.top()->
is_disposed() || m_queue.top()->get_timepoint() <= now);
97 void base_dispose_impl(interface_disposable::Mode)
noexcept override
100 std::lock_guard lock{m_mutex};
107 std::mutex m_mutex{};
110 std::condition_variable m_cv{};
113 class worker_strategy
116 worker_strategy(
const std::weak_ptr<state_t>& state)
122 void defer_to(time_point tp, Fn&& fn, Handler&& handler, Args&&... args)
const
124 if (
const auto shared = m_state.lock())
125 shared->emplace_and_notify(tp, std::forward<Fn>(fn), std::forward<Handler>(handler), std::forward<Args>(args)...);
128 static rpp::schedulers::time_point now() {
return details::now(); }
131 std::weak_ptr<state_t> m_state;
135 bool is_empty()
const
137 return m_state->is_empty();
140 bool is_any_ready_schedulable()
const
142 return m_state->is_any_ready_schedulable();
145 void dispatch_if_ready()
const
147 dispatch_impl(
false);
150 void dispatch()
const
161 void dispatch_impl(
bool wait)
const
163 if (
auto top = m_state->pop(wait))
165 if (top->is_disposed())
168 if (
const auto timepoint = (*top)())
169 m_state->emplace_and_notify(timepoint.value(), std::move(top));
174 std::shared_ptr<state_t> m_state = std::make_shared<state_t>();