1  
//
1  
//
2  
// Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
2  
// Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3  
// Copyright (c) 2026 Steve Gerbino
3  
// Copyright (c) 2026 Steve Gerbino
4  
//
4  
//
5  
// Distributed under the Boost Software License, Version 1.0. (See accompanying
5  
// Distributed under the Boost Software License, Version 1.0. (See accompanying
6  
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6  
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7  
//
7  
//
8  
// Official repository: https://github.com/cppalliance/corosio
8  
// Official repository: https://github.com/cppalliance/corosio
9  
//
9  
//
10  

10  

11  
#ifndef BOOST_COROSIO_DETAIL_TIMER_SERVICE_HPP
11  
#ifndef BOOST_COROSIO_DETAIL_TIMER_SERVICE_HPP
12  
#define BOOST_COROSIO_DETAIL_TIMER_SERVICE_HPP
12  
#define BOOST_COROSIO_DETAIL_TIMER_SERVICE_HPP
13  

13  

14  
#include <boost/corosio/timer.hpp>
14  
#include <boost/corosio/timer.hpp>
15  
#include <boost/corosio/io_context.hpp>
15  
#include <boost/corosio/io_context.hpp>
16  
#include <boost/corosio/detail/scheduler_op.hpp>
16  
#include <boost/corosio/detail/scheduler_op.hpp>
17  
#include <boost/corosio/native/native_scheduler.hpp>
17  
#include <boost/corosio/native/native_scheduler.hpp>
18  
#include <boost/corosio/detail/intrusive.hpp>
18  
#include <boost/corosio/detail/intrusive.hpp>
19  
#include <boost/corosio/detail/thread_local_ptr.hpp>
19  
#include <boost/corosio/detail/thread_local_ptr.hpp>
20  
#include <boost/capy/error.hpp>
20  
#include <boost/capy/error.hpp>
21  
#include <boost/capy/ex/execution_context.hpp>
21  
#include <boost/capy/ex/execution_context.hpp>
22  
#include <boost/capy/ex/executor_ref.hpp>
22  
#include <boost/capy/ex/executor_ref.hpp>
23  
#include <system_error>
23  
#include <system_error>
24  

24  

25  
#include <atomic>
25  
#include <atomic>
26  
#include <chrono>
26  
#include <chrono>
27  
#include <coroutine>
27  
#include <coroutine>
28  
#include <cstddef>
28  
#include <cstddef>
29  
#include <limits>
29  
#include <limits>
30  
#include <mutex>
30  
#include <mutex>
31  
#include <optional>
31  
#include <optional>
32  
#include <stop_token>
32  
#include <stop_token>
33  
#include <utility>
33  
#include <utility>
34  
#include <vector>
34  
#include <vector>
35  

35  

36  
namespace boost::corosio::detail {
36  
namespace boost::corosio::detail {
37  

37  

38  
struct scheduler;
38  
struct scheduler;
39  

39  

40  
/*
40  
/*
41  
    Timer Service
41  
    Timer Service
42  
    =============
42  
    =============
43  

43  

44  
    Data Structures
44  
    Data Structures
45  
    ---------------
45  
    ---------------
46  
    waiter_node holds per-waiter state: coroutine handle, executor,
46  
    waiter_node holds per-waiter state: coroutine handle, executor,
47  
    error output, stop_token, embedded completion_op. Each concurrent
47  
    error output, stop_token, embedded completion_op. Each concurrent
48  
    co_await t.wait() allocates one waiter_node.
48  
    co_await t.wait() allocates one waiter_node.
49  

49  

50  
    timer_service::implementation holds per-timer state: expiry,
50  
    timer_service::implementation holds per-timer state: expiry,
51  
    heap index, and an intrusive_list of waiter_nodes. Multiple
51  
    heap index, and an intrusive_list of waiter_nodes. Multiple
52  
    coroutines can wait on the same timer simultaneously.
52  
    coroutines can wait on the same timer simultaneously.
53  

53  

54  
    timer_service owns a min-heap of active timers, a free list
54  
    timer_service owns a min-heap of active timers, a free list
55  
    of recycled impls, and a free list of recycled waiter_nodes. The
55  
    of recycled impls, and a free list of recycled waiter_nodes. The
56  
    heap is ordered by expiry time; the scheduler queries
56  
    heap is ordered by expiry time; the scheduler queries
57  
    nearest_expiry() to set the epoll/timerfd timeout.
57  
    nearest_expiry() to set the epoll/timerfd timeout.
58  

58  

59  
    Optimization Strategy
59  
    Optimization Strategy
60  
    ---------------------
60  
    ---------------------
61  
    1. Deferred heap insertion — expires_after() stores the expiry
61  
    1. Deferred heap insertion — expires_after() stores the expiry
62  
       but does not insert into the heap. Insertion happens in wait().
62  
       but does not insert into the heap. Insertion happens in wait().
63  
    2. Thread-local impl cache — single-slot per-thread cache.
63  
    2. Thread-local impl cache — single-slot per-thread cache.
64  
    3. Embedded completion_op — eliminates heap allocation per fire/cancel.
64  
    3. Embedded completion_op — eliminates heap allocation per fire/cancel.
65  
    4. Cached nearest expiry — atomic avoids mutex in nearest_expiry().
65  
    4. Cached nearest expiry — atomic avoids mutex in nearest_expiry().
66  
    5. might_have_pending_waits_ flag — skips lock when no wait issued.
66  
    5. might_have_pending_waits_ flag — skips lock when no wait issued.
67  
    6. Thread-local waiter cache — single-slot per-thread cache.
67  
    6. Thread-local waiter cache — single-slot per-thread cache.
68  

68  

69  
    Concurrency
69  
    Concurrency
70  
    -----------
70  
    -----------
71  
    stop_token callbacks can fire from any thread. The impl_
71  
    stop_token callbacks can fire from any thread. The impl_
72  
    pointer on waiter_node is used as a "still in list" marker.
72  
    pointer on waiter_node is used as a "still in list" marker.
73  
*/
73  
*/
74  

74  

75  
struct BOOST_COROSIO_SYMBOL_VISIBLE waiter_node;
75  
struct BOOST_COROSIO_SYMBOL_VISIBLE waiter_node;
76  

76  

77  
inline void timer_service_invalidate_cache() noexcept;
77  
inline void timer_service_invalidate_cache() noexcept;
78  

78  

79  
// timer_service class body — member function definitions are
79  
// timer_service class body — member function definitions are
80  
// out-of-class (after implementation and waiter_node are complete)
80  
// out-of-class (after implementation and waiter_node are complete)
81  
class BOOST_COROSIO_DECL timer_service final
81  
class BOOST_COROSIO_DECL timer_service final
82  
    : public capy::execution_context::service
82  
    : public capy::execution_context::service
83  
    , public io_object::io_service
83  
    , public io_object::io_service
84  
{
84  
{
85  
public:
85  
public:
86  
    using clock_type = std::chrono::steady_clock;
86  
    using clock_type = std::chrono::steady_clock;
87  
    using time_point = clock_type::time_point;
87  
    using time_point = clock_type::time_point;
88  

88  

89  
    class callback
89  
    class callback
90  
    {
90  
    {
91  
        void* ctx_         = nullptr;
91  
        void* ctx_         = nullptr;
92  
        void (*fn_)(void*) = nullptr;
92  
        void (*fn_)(void*) = nullptr;
93  

93  

94  
    public:
94  
    public:
95  
        callback() = default;
95  
        callback() = default;
96  
        callback(void* ctx, void (*fn)(void*)) noexcept : ctx_(ctx), fn_(fn) {}
96  
        callback(void* ctx, void (*fn)(void*)) noexcept : ctx_(ctx), fn_(fn) {}
97  

97  

98  
        explicit operator bool() const noexcept
98  
        explicit operator bool() const noexcept
99  
        {
99  
        {
100  
            return fn_ != nullptr;
100  
            return fn_ != nullptr;
101  
        }
101  
        }
102  
        void operator()() const
102  
        void operator()() const
103  
        {
103  
        {
104  
            if (fn_)
104  
            if (fn_)
105  
                fn_(ctx_);
105  
                fn_(ctx_);
106  
        }
106  
        }
107  
    };
107  
    };
108  

108  

109  
    struct implementation;
109  
    struct implementation;
110  

110  

111  
private:
111  
private:
112  
    struct heap_entry
112  
    struct heap_entry
113  
    {
113  
    {
114  
        time_point time_;
114  
        time_point time_;
115  
        implementation* timer_;
115  
        implementation* timer_;
116  
    };
116  
    };
117  

117  

118  
    scheduler* sched_ = nullptr;
118  
    scheduler* sched_ = nullptr;
119  
    mutable std::mutex mutex_;
119  
    mutable std::mutex mutex_;
120  
    std::vector<heap_entry> heap_;
120  
    std::vector<heap_entry> heap_;
121  
    implementation* free_list_     = nullptr;
121  
    implementation* free_list_     = nullptr;
122  
    waiter_node* waiter_free_list_ = nullptr;
122  
    waiter_node* waiter_free_list_ = nullptr;
123  
    callback on_earliest_changed_;
123  
    callback on_earliest_changed_;
124  
    // Avoids mutex in nearest_expiry() and empty()
124  
    // Avoids mutex in nearest_expiry() and empty()
125  
    mutable std::atomic<std::int64_t> cached_nearest_ns_{
125  
    mutable std::atomic<std::int64_t> cached_nearest_ns_{
126  
        (std::numeric_limits<std::int64_t>::max)()};
126  
        (std::numeric_limits<std::int64_t>::max)()};
127  

127  

128  
public:
128  
public:
129  
    inline timer_service(capy::execution_context&, scheduler& sched)
129  
    inline timer_service(capy::execution_context&, scheduler& sched)
130  
        : sched_(&sched)
130  
        : sched_(&sched)
131  
    {
131  
    {
132  
    }
132  
    }
133  

133  

134  
    inline scheduler& get_scheduler() noexcept
134  
    inline scheduler& get_scheduler() noexcept
135  
    {
135  
    {
136  
        return *sched_;
136  
        return *sched_;
137  
    }
137  
    }
138  

138  

139  
    ~timer_service() override = default;
139  
    ~timer_service() override = default;
140  

140  

141  
    timer_service(timer_service const&)            = delete;
141  
    timer_service(timer_service const&)            = delete;
142  
    timer_service& operator=(timer_service const&) = delete;
142  
    timer_service& operator=(timer_service const&) = delete;
143  

143  

144  
    inline void set_on_earliest_changed(callback cb)
144  
    inline void set_on_earliest_changed(callback cb)
145  
    {
145  
    {
146  
        on_earliest_changed_ = cb;
146  
        on_earliest_changed_ = cb;
147  
    }
147  
    }
148  

148  

149  
    inline bool empty() const noexcept
149  
    inline bool empty() const noexcept
150  
    {
150  
    {
151  
        return cached_nearest_ns_.load(std::memory_order_acquire) ==
151  
        return cached_nearest_ns_.load(std::memory_order_acquire) ==
152  
            (std::numeric_limits<std::int64_t>::max)();
152  
            (std::numeric_limits<std::int64_t>::max)();
153  
    }
153  
    }
154  

154  

155  
    inline time_point nearest_expiry() const noexcept
155  
    inline time_point nearest_expiry() const noexcept
156  
    {
156  
    {
157  
        auto ns = cached_nearest_ns_.load(std::memory_order_acquire);
157  
        auto ns = cached_nearest_ns_.load(std::memory_order_acquire);
158  
        return time_point(time_point::duration(ns));
158  
        return time_point(time_point::duration(ns));
159  
    }
159  
    }
160  

160  

161  
    inline void shutdown() override;
161  
    inline void shutdown() override;
162  
    inline io_object::implementation* construct() override;
162  
    inline io_object::implementation* construct() override;
163  
    inline void destroy(io_object::implementation* p) override;
163  
    inline void destroy(io_object::implementation* p) override;
164  
    inline void destroy_impl(implementation& impl);
164  
    inline void destroy_impl(implementation& impl);
165  
    inline waiter_node* create_waiter();
165  
    inline waiter_node* create_waiter();
166  
    inline void destroy_waiter(waiter_node* w);
166  
    inline void destroy_waiter(waiter_node* w);
167  
    inline std::size_t update_timer(implementation& impl, time_point new_time);
167  
    inline std::size_t update_timer(implementation& impl, time_point new_time);
168  
    inline void insert_waiter(implementation& impl, waiter_node* w);
168  
    inline void insert_waiter(implementation& impl, waiter_node* w);
169  
    inline std::size_t cancel_timer(implementation& impl);
169  
    inline std::size_t cancel_timer(implementation& impl);
170  
    inline void cancel_waiter(waiter_node* w);
170  
    inline void cancel_waiter(waiter_node* w);
171  
    inline std::size_t cancel_one_waiter(implementation& impl);
171  
    inline std::size_t cancel_one_waiter(implementation& impl);
172  
    inline std::size_t process_expired();
172  
    inline std::size_t process_expired();
173  

173  

174  
private:
174  
private:
175  
    inline void refresh_cached_nearest() noexcept
175  
    inline void refresh_cached_nearest() noexcept
176  
    {
176  
    {
177  
        auto ns = heap_.empty() ? (std::numeric_limits<std::int64_t>::max)()
177  
        auto ns = heap_.empty() ? (std::numeric_limits<std::int64_t>::max)()
178  
                                : heap_[0].time_.time_since_epoch().count();
178  
                                : heap_[0].time_.time_since_epoch().count();
179  
        cached_nearest_ns_.store(ns, std::memory_order_release);
179  
        cached_nearest_ns_.store(ns, std::memory_order_release);
180  
    }
180  
    }
181  

181  

182  
    inline void remove_timer_impl(implementation& impl);
182  
    inline void remove_timer_impl(implementation& impl);
183  
    inline void up_heap(std::size_t index);
183  
    inline void up_heap(std::size_t index);
184  
    inline void down_heap(std::size_t index);
184  
    inline void down_heap(std::size_t index);
185  
    inline void swap_heap(std::size_t i1, std::size_t i2);
185  
    inline void swap_heap(std::size_t i1, std::size_t i2);
186  
};
186  
};
187  

187  

188  
struct BOOST_COROSIO_SYMBOL_VISIBLE waiter_node
188  
struct BOOST_COROSIO_SYMBOL_VISIBLE waiter_node
189  
    : intrusive_list<waiter_node>::node
189  
    : intrusive_list<waiter_node>::node
190  
{
190  
{
191  
    // Embedded completion op — avoids heap allocation per fire/cancel
191  
    // Embedded completion op — avoids heap allocation per fire/cancel
192  
    struct completion_op final : scheduler_op
192  
    struct completion_op final : scheduler_op
193  
    {
193  
    {
194  
        waiter_node* waiter_ = nullptr;
194  
        waiter_node* waiter_ = nullptr;
195  

195  

196  
        static void do_complete(
196  
        static void do_complete(
197  
            void* owner, scheduler_op* base, std::uint32_t, std::uint32_t);
197  
            void* owner, scheduler_op* base, std::uint32_t, std::uint32_t);
198  

198  

199  
        completion_op() noexcept : scheduler_op(&do_complete) {}
199  
        completion_op() noexcept : scheduler_op(&do_complete) {}
200  

200  

201  
        void operator()() override;
201  
        void operator()() override;
202  
        void destroy() override;
202  
        void destroy() override;
203  
    };
203  
    };
204  

204  

205  
    // Per-waiter stop_token cancellation
205  
    // Per-waiter stop_token cancellation
206  
    struct canceller
206  
    struct canceller
207  
    {
207  
    {
208  
        waiter_node* waiter_;
208  
        waiter_node* waiter_;
209  
        void operator()() const;
209  
        void operator()() const;
210  
    };
210  
    };
211  

211  

212  
    // nullptr once removed from timer's waiter list (concurrency marker)
212  
    // nullptr once removed from timer's waiter list (concurrency marker)
213  
    timer_service::implementation* impl_ = nullptr;
213  
    timer_service::implementation* impl_ = nullptr;
214  
    timer_service* svc_                  = nullptr;
214  
    timer_service* svc_                  = nullptr;
215  
    std::coroutine_handle<> h_;
215  
    std::coroutine_handle<> h_;
216  
    capy::executor_ref d_;
216  
    capy::executor_ref d_;
217  
    std::error_code* ec_out_ = nullptr;
217  
    std::error_code* ec_out_ = nullptr;
218  
    std::stop_token token_;
218  
    std::stop_token token_;
219  
    std::optional<std::stop_callback<canceller>> stop_cb_;
219  
    std::optional<std::stop_callback<canceller>> stop_cb_;
220  
    completion_op op_;
220  
    completion_op op_;
221  
    std::error_code ec_value_;
221  
    std::error_code ec_value_;
222  
    waiter_node* next_free_ = nullptr;
222  
    waiter_node* next_free_ = nullptr;
223  

223  

224  
    waiter_node() noexcept
224  
    waiter_node() noexcept
225  
    {
225  
    {
226  
        op_.waiter_ = this;
226  
        op_.waiter_ = this;
227  
    }
227  
    }
228  
};
228  
};
229  

229  

230  
struct timer_service::implementation final : timer::implementation
230  
struct timer_service::implementation final : timer::implementation
231  
{
231  
{
232  
    using clock_type = std::chrono::steady_clock;
232  
    using clock_type = std::chrono::steady_clock;
233  
    using time_point = clock_type::time_point;
233  
    using time_point = clock_type::time_point;
234  
    using duration   = clock_type::duration;
234  
    using duration   = clock_type::duration;
235  

235  

236  
    timer_service* svc_ = nullptr;
236  
    timer_service* svc_ = nullptr;
237  
    intrusive_list<waiter_node> waiters_;
237  
    intrusive_list<waiter_node> waiters_;
238  

238  

239  
    // Free list linkage (reused when impl is on free_list)
239  
    // Free list linkage (reused when impl is on free_list)
240  
    implementation* next_free_ = nullptr;
240  
    implementation* next_free_ = nullptr;
241  

241  

242  
    inline explicit implementation(timer_service& svc) noexcept;
242  
    inline explicit implementation(timer_service& svc) noexcept;
243  

243  

244  
    inline std::coroutine_handle<> wait(
244  
    inline std::coroutine_handle<> wait(
245  
        std::coroutine_handle<>,
245  
        std::coroutine_handle<>,
246  
        capy::executor_ref,
246  
        capy::executor_ref,
247  
        std::stop_token,
247  
        std::stop_token,
248  
        std::error_code*) override;
248  
        std::error_code*) override;
249  
};
249  
};
250  

250  

251  
// Thread-local caches avoid hot-path mutex acquisitions:
251  
// Thread-local caches avoid hot-path mutex acquisitions:
252  
// 1. Impl cache — single-slot, validated by comparing svc_
252  
// 1. Impl cache — single-slot, validated by comparing svc_
253  
// 2. Waiter cache — single-slot, no service affinity
253  
// 2. Waiter cache — single-slot, no service affinity
254  
// All caches are cleared by timer_service_invalidate_cache() during shutdown.
254  
// All caches are cleared by timer_service_invalidate_cache() during shutdown.
255  

255  

256  
inline thread_local_ptr<timer_service::implementation> tl_cached_impl;
256  
inline thread_local_ptr<timer_service::implementation> tl_cached_impl;
257  
inline thread_local_ptr<waiter_node> tl_cached_waiter;
257  
inline thread_local_ptr<waiter_node> tl_cached_waiter;
258  

258  

259  
inline timer_service::implementation*
259  
inline timer_service::implementation*
260  
try_pop_tl_cache(timer_service* svc) noexcept
260  
try_pop_tl_cache(timer_service* svc) noexcept
261  
{
261  
{
262  
    auto* impl = tl_cached_impl.get();
262  
    auto* impl = tl_cached_impl.get();
263  
    if (impl)
263  
    if (impl)
264  
    {
264  
    {
265  
        tl_cached_impl.set(nullptr);
265  
        tl_cached_impl.set(nullptr);
266  
        if (impl->svc_ == svc)
266  
        if (impl->svc_ == svc)
267  
            return impl;
267  
            return impl;
268  
        // Stale impl from a destroyed service
268  
        // Stale impl from a destroyed service
269  
        delete impl;
269  
        delete impl;
270  
    }
270  
    }
271  
    return nullptr;
271  
    return nullptr;
272  
}
272  
}
273  

273  

274  
inline bool
274  
inline bool
275  
try_push_tl_cache(timer_service::implementation* impl) noexcept
275  
try_push_tl_cache(timer_service::implementation* impl) noexcept
276  
{
276  
{
277  
    if (!tl_cached_impl.get())
277  
    if (!tl_cached_impl.get())
278  
    {
278  
    {
279  
        tl_cached_impl.set(impl);
279  
        tl_cached_impl.set(impl);
280  
        return true;
280  
        return true;
281  
    }
281  
    }
282  
    return false;
282  
    return false;
283  
}
283  
}
284  

284  

285  
inline waiter_node*
285  
inline waiter_node*
286  
try_pop_waiter_tl_cache() noexcept
286  
try_pop_waiter_tl_cache() noexcept
287  
{
287  
{
288  
    auto* w = tl_cached_waiter.get();
288  
    auto* w = tl_cached_waiter.get();
289  
    if (w)
289  
    if (w)
290  
    {
290  
    {
291  
        tl_cached_waiter.set(nullptr);
291  
        tl_cached_waiter.set(nullptr);
292  
        return w;
292  
        return w;
293  
    }
293  
    }
294  
    return nullptr;
294  
    return nullptr;
295  
}
295  
}
296  

296  

297  
inline bool
297  
inline bool
298  
try_push_waiter_tl_cache(waiter_node* w) noexcept
298  
try_push_waiter_tl_cache(waiter_node* w) noexcept
299  
{
299  
{
300  
    if (!tl_cached_waiter.get())
300  
    if (!tl_cached_waiter.get())
301  
    {
301  
    {
302  
        tl_cached_waiter.set(w);
302  
        tl_cached_waiter.set(w);
303  
        return true;
303  
        return true;
304  
    }
304  
    }
305  
    return false;
305  
    return false;
306  
}
306  
}
307  

307  

308  
inline void
308  
inline void
309  
timer_service_invalidate_cache() noexcept
309  
timer_service_invalidate_cache() noexcept
310  
{
310  
{
311  
    delete tl_cached_impl.get();
311  
    delete tl_cached_impl.get();
312  
    tl_cached_impl.set(nullptr);
312  
    tl_cached_impl.set(nullptr);
313  

313  

314  
    delete tl_cached_waiter.get();
314  
    delete tl_cached_waiter.get();
315  
    tl_cached_waiter.set(nullptr);
315  
    tl_cached_waiter.set(nullptr);
316  
}
316  
}
317  

317  

318  
// timer_service out-of-class member function definitions
318  
// timer_service out-of-class member function definitions
319  

319  

320  
inline timer_service::implementation::implementation(
320  
inline timer_service::implementation::implementation(
321  
    timer_service& svc) noexcept
321  
    timer_service& svc) noexcept
322  
    : svc_(&svc)
322  
    : svc_(&svc)
323  
{
323  
{
324  
}
324  
}
325  

325  

326  
inline void
326  
inline void
327  
timer_service::shutdown()
327  
timer_service::shutdown()
328  
{
328  
{
329  
    timer_service_invalidate_cache();
329  
    timer_service_invalidate_cache();
330  

330  

331  
    // Cancel waiting timers still in the heap.
331  
    // Cancel waiting timers still in the heap.
332  
    // Each waiter called work_started() in implementation::wait().
332  
    // Each waiter called work_started() in implementation::wait().
333  
    // On IOCP the scheduler shutdown loop exits when outstanding_work_
333  
    // On IOCP the scheduler shutdown loop exits when outstanding_work_
334  
    // reaches zero, so we must call work_finished() here to balance it.
334  
    // reaches zero, so we must call work_finished() here to balance it.
335  
    // On other backends this is harmless (their drain loops exit when
335  
    // On other backends this is harmless (their drain loops exit when
336  
    // the queue is empty, not based on outstanding_work_).
336  
    // the queue is empty, not based on outstanding_work_).
337  
    for (auto& entry : heap_)
337  
    for (auto& entry : heap_)
338  
    {
338  
    {
339  
        auto* impl = entry.timer_;
339  
        auto* impl = entry.timer_;
340  
        while (auto* w = impl->waiters_.pop_front())
340  
        while (auto* w = impl->waiters_.pop_front())
341  
        {
341  
        {
342  
            w->stop_cb_.reset();
342  
            w->stop_cb_.reset();
343  
            auto h = std::exchange(w->h_, {});
343  
            auto h = std::exchange(w->h_, {});
344  
            sched_->work_finished();
344  
            sched_->work_finished();
345  
            if (h)
345  
            if (h)
346  
                h.destroy();
346  
                h.destroy();
347  
            delete w;
347  
            delete w;
348  
        }
348  
        }
349  
        impl->heap_index_ = (std::numeric_limits<std::size_t>::max)();
349  
        impl->heap_index_ = (std::numeric_limits<std::size_t>::max)();
350  
        delete impl;
350  
        delete impl;
351  
    }
351  
    }
352  
    heap_.clear();
352  
    heap_.clear();
353  
    cached_nearest_ns_.store(
353  
    cached_nearest_ns_.store(
354  
        (std::numeric_limits<std::int64_t>::max)(), std::memory_order_release);
354  
        (std::numeric_limits<std::int64_t>::max)(), std::memory_order_release);
355  

355  

356  
    // Delete free-listed impls
356  
    // Delete free-listed impls
357  
    while (free_list_)
357  
    while (free_list_)
358  
    {
358  
    {
359  
        auto* next = free_list_->next_free_;
359  
        auto* next = free_list_->next_free_;
360  
        delete free_list_;
360  
        delete free_list_;
361  
        free_list_ = next;
361  
        free_list_ = next;
362  
    }
362  
    }
363  

363  

364  
    // Delete free-listed waiters
364  
    // Delete free-listed waiters
365  
    while (waiter_free_list_)
365  
    while (waiter_free_list_)
366  
    {
366  
    {
367  
        auto* next = waiter_free_list_->next_free_;
367  
        auto* next = waiter_free_list_->next_free_;
368  
        delete waiter_free_list_;
368  
        delete waiter_free_list_;
369  
        waiter_free_list_ = next;
369  
        waiter_free_list_ = next;
370  
    }
370  
    }
371  
}
371  
}
372  

372  

373  
inline io_object::implementation*
373  
inline io_object::implementation*
374  
timer_service::construct()
374  
timer_service::construct()
375  
{
375  
{
376  
    implementation* impl = try_pop_tl_cache(this);
376  
    implementation* impl = try_pop_tl_cache(this);
377  
    if (impl)
377  
    if (impl)
378  
    {
378  
    {
379  
        impl->svc_        = this;
379  
        impl->svc_        = this;
380  
        impl->heap_index_ = (std::numeric_limits<std::size_t>::max)();
380  
        impl->heap_index_ = (std::numeric_limits<std::size_t>::max)();
381  
        impl->might_have_pending_waits_ = false;
381  
        impl->might_have_pending_waits_ = false;
382  
        return impl;
382  
        return impl;
383  
    }
383  
    }
384  

384  

385  
    std::lock_guard lock(mutex_);
385  
    std::lock_guard lock(mutex_);
386  
    if (free_list_)
386  
    if (free_list_)
387  
    {
387  
    {
388  
        impl              = free_list_;
388  
        impl              = free_list_;
389  
        free_list_        = impl->next_free_;
389  
        free_list_        = impl->next_free_;
390  
        impl->next_free_  = nullptr;
390  
        impl->next_free_  = nullptr;
391  
        impl->svc_        = this;
391  
        impl->svc_        = this;
392  
        impl->heap_index_ = (std::numeric_limits<std::size_t>::max)();
392  
        impl->heap_index_ = (std::numeric_limits<std::size_t>::max)();
393  
        impl->might_have_pending_waits_ = false;
393  
        impl->might_have_pending_waits_ = false;
394  
    }
394  
    }
395  
    else
395  
    else
396  
    {
396  
    {
397  
        impl = new implementation(*this);
397  
        impl = new implementation(*this);
398  
    }
398  
    }
399  
    return impl;
399  
    return impl;
400  
}
400  
}
401  

401  

402  
inline void
402  
inline void
403  
timer_service::destroy(io_object::implementation* p)
403  
timer_service::destroy(io_object::implementation* p)
404  
{
404  
{
405  
    destroy_impl(static_cast<implementation&>(*p));
405  
    destroy_impl(static_cast<implementation&>(*p));
406  
}
406  
}
407  

407  

408  
inline void
408  
inline void
409  
timer_service::destroy_impl(implementation& impl)
409  
timer_service::destroy_impl(implementation& impl)
410  
{
410  
{
411  
    cancel_timer(impl);
411  
    cancel_timer(impl);
412  

412  

413  
    if (impl.heap_index_ != (std::numeric_limits<std::size_t>::max)())
413  
    if (impl.heap_index_ != (std::numeric_limits<std::size_t>::max)())
414  
    {
414  
    {
415  
        std::lock_guard lock(mutex_);
415  
        std::lock_guard lock(mutex_);
416  
        remove_timer_impl(impl);
416  
        remove_timer_impl(impl);
417  
        refresh_cached_nearest();
417  
        refresh_cached_nearest();
418  
    }
418  
    }
419  

419  

420  
    if (try_push_tl_cache(&impl))
420  
    if (try_push_tl_cache(&impl))
421  
        return;
421  
        return;
422  

422  

423  
    std::lock_guard lock(mutex_);
423  
    std::lock_guard lock(mutex_);
424  
    impl.next_free_ = free_list_;
424  
    impl.next_free_ = free_list_;
425  
    free_list_      = &impl;
425  
    free_list_      = &impl;
426  
}
426  
}
427  

427  

428  
inline waiter_node*
428  
inline waiter_node*
429  
timer_service::create_waiter()
429  
timer_service::create_waiter()
430  
{
430  
{
431  
    if (auto* w = try_pop_waiter_tl_cache())
431  
    if (auto* w = try_pop_waiter_tl_cache())
432  
        return w;
432  
        return w;
433  

433  

434  
    std::lock_guard lock(mutex_);
434  
    std::lock_guard lock(mutex_);
435  
    if (waiter_free_list_)
435  
    if (waiter_free_list_)
436  
    {
436  
    {
437  
        auto* w           = waiter_free_list_;
437  
        auto* w           = waiter_free_list_;
438  
        waiter_free_list_ = w->next_free_;
438  
        waiter_free_list_ = w->next_free_;
439  
        w->next_free_     = nullptr;
439  
        w->next_free_     = nullptr;
440  
        return w;
440  
        return w;
441  
    }
441  
    }
442  

442  

443  
    return new waiter_node();
443  
    return new waiter_node();
444  
}
444  
}
445  

445  

446  
inline void
446  
inline void
447  
timer_service::destroy_waiter(waiter_node* w)
447  
timer_service::destroy_waiter(waiter_node* w)
448  
{
448  
{
449  
    if (try_push_waiter_tl_cache(w))
449  
    if (try_push_waiter_tl_cache(w))
450  
        return;
450  
        return;
451  

451  

452  
    std::lock_guard lock(mutex_);
452  
    std::lock_guard lock(mutex_);
453  
    w->next_free_     = waiter_free_list_;
453  
    w->next_free_     = waiter_free_list_;
454  
    waiter_free_list_ = w;
454  
    waiter_free_list_ = w;
455  
}
455  
}
456  

456  

457  
inline std::size_t
457  
inline std::size_t
458  
timer_service::update_timer(implementation& impl, time_point new_time)
458  
timer_service::update_timer(implementation& impl, time_point new_time)
459  
{
459  
{
460  
    bool in_heap =
460  
    bool in_heap =
461  
        (impl.heap_index_ != (std::numeric_limits<std::size_t>::max)());
461  
        (impl.heap_index_ != (std::numeric_limits<std::size_t>::max)());
462  
    if (!in_heap && impl.waiters_.empty())
462  
    if (!in_heap && impl.waiters_.empty())
463  
        return 0;
463  
        return 0;
464  

464  

465  
    bool notify = false;
465  
    bool notify = false;
466  
    intrusive_list<waiter_node> canceled;
466  
    intrusive_list<waiter_node> canceled;
467  

467  

468  
    {
468  
    {
469  
        std::lock_guard lock(mutex_);
469  
        std::lock_guard lock(mutex_);
470  

470  

471  
        while (auto* w = impl.waiters_.pop_front())
471  
        while (auto* w = impl.waiters_.pop_front())
472  
        {
472  
        {
473  
            w->impl_ = nullptr;
473  
            w->impl_ = nullptr;
474  
            canceled.push_back(w);
474  
            canceled.push_back(w);
475  
        }
475  
        }
476  

476  

477  
        if (impl.heap_index_ < heap_.size())
477  
        if (impl.heap_index_ < heap_.size())
478  
        {
478  
        {
479  
            time_point old_time           = heap_[impl.heap_index_].time_;
479  
            time_point old_time           = heap_[impl.heap_index_].time_;
480  
            heap_[impl.heap_index_].time_ = new_time;
480  
            heap_[impl.heap_index_].time_ = new_time;
481  

481  

482  
            if (new_time < old_time)
482  
            if (new_time < old_time)
483  
                up_heap(impl.heap_index_);
483  
                up_heap(impl.heap_index_);
484  
            else
484  
            else
485  
                down_heap(impl.heap_index_);
485  
                down_heap(impl.heap_index_);
486  

486  

487  
            notify = (impl.heap_index_ == 0);
487  
            notify = (impl.heap_index_ == 0);
488  
        }
488  
        }
489  

489  

490  
        refresh_cached_nearest();
490  
        refresh_cached_nearest();
491  
    }
491  
    }
492  

492  

493  
    std::size_t count = 0;
493  
    std::size_t count = 0;
494  
    while (auto* w = canceled.pop_front())
494  
    while (auto* w = canceled.pop_front())
495  
    {
495  
    {
496  
        w->ec_value_ = make_error_code(capy::error::canceled);
496  
        w->ec_value_ = make_error_code(capy::error::canceled);
497  
        sched_->post(&w->op_);
497  
        sched_->post(&w->op_);
498  
        ++count;
498  
        ++count;
499  
    }
499  
    }
500  

500  

501  
    if (notify)
501  
    if (notify)
502  
        on_earliest_changed_();
502  
        on_earliest_changed_();
503  

503  

504  
    return count;
504  
    return count;
505  
}
505  
}
506  

506  

507  
inline void
507  
inline void
508  
timer_service::insert_waiter(implementation& impl, waiter_node* w)
508  
timer_service::insert_waiter(implementation& impl, waiter_node* w)
509  
{
509  
{
510  
    bool notify = false;
510  
    bool notify = false;
511  
    {
511  
    {
512  
        std::lock_guard lock(mutex_);
512  
        std::lock_guard lock(mutex_);
513  
        if (impl.heap_index_ == (std::numeric_limits<std::size_t>::max)())
513  
        if (impl.heap_index_ == (std::numeric_limits<std::size_t>::max)())
514  
        {
514  
        {
515  
            impl.heap_index_ = heap_.size();
515  
            impl.heap_index_ = heap_.size();
516  
            heap_.push_back({impl.expiry_, &impl});
516  
            heap_.push_back({impl.expiry_, &impl});
517  
            up_heap(heap_.size() - 1);
517  
            up_heap(heap_.size() - 1);
518  
            notify = (impl.heap_index_ == 0);
518  
            notify = (impl.heap_index_ == 0);
519  
            refresh_cached_nearest();
519  
            refresh_cached_nearest();
520  
        }
520  
        }
521  
        impl.waiters_.push_back(w);
521  
        impl.waiters_.push_back(w);
522  
    }
522  
    }
523  
    if (notify)
523  
    if (notify)
524  
        on_earliest_changed_();
524  
        on_earliest_changed_();
525  
}
525  
}
526  

526  

527  
inline std::size_t
527  
inline std::size_t
528  
timer_service::cancel_timer(implementation& impl)
528  
timer_service::cancel_timer(implementation& impl)
529  
{
529  
{
530  
    if (!impl.might_have_pending_waits_)
530  
    if (!impl.might_have_pending_waits_)
531  
        return 0;
531  
        return 0;
532  

532  

533  
    // Not in heap and no waiters — just clear the flag
533  
    // Not in heap and no waiters — just clear the flag
534  
    if (impl.heap_index_ == (std::numeric_limits<std::size_t>::max)() &&
534  
    if (impl.heap_index_ == (std::numeric_limits<std::size_t>::max)() &&
535  
        impl.waiters_.empty())
535  
        impl.waiters_.empty())
536  
    {
536  
    {
537  
        impl.might_have_pending_waits_ = false;
537  
        impl.might_have_pending_waits_ = false;
538  
        return 0;
538  
        return 0;
539  
    }
539  
    }
540  

540  

541  
    intrusive_list<waiter_node> canceled;
541  
    intrusive_list<waiter_node> canceled;
542  

542  

543  
    {
543  
    {
544  
        std::lock_guard lock(mutex_);
544  
        std::lock_guard lock(mutex_);
545  
        remove_timer_impl(impl);
545  
        remove_timer_impl(impl);
546  
        while (auto* w = impl.waiters_.pop_front())
546  
        while (auto* w = impl.waiters_.pop_front())
547  
        {
547  
        {
548  
            w->impl_ = nullptr;
548  
            w->impl_ = nullptr;
549  
            canceled.push_back(w);
549  
            canceled.push_back(w);
550  
        }
550  
        }
551  
        refresh_cached_nearest();
551  
        refresh_cached_nearest();
552  
    }
552  
    }
553  

553  

554  
    impl.might_have_pending_waits_ = false;
554  
    impl.might_have_pending_waits_ = false;
555  

555  

556  
    std::size_t count = 0;
556  
    std::size_t count = 0;
557  
    while (auto* w = canceled.pop_front())
557  
    while (auto* w = canceled.pop_front())
558  
    {
558  
    {
559  
        w->ec_value_ = make_error_code(capy::error::canceled);
559  
        w->ec_value_ = make_error_code(capy::error::canceled);
560  
        sched_->post(&w->op_);
560  
        sched_->post(&w->op_);
561  
        ++count;
561  
        ++count;
562  
    }
562  
    }
563  

563  

564  
    return count;
564  
    return count;
565  
}
565  
}
566  

566  

567  
inline void
567  
inline void
568  
timer_service::cancel_waiter(waiter_node* w)
568  
timer_service::cancel_waiter(waiter_node* w)
569  
{
569  
{
570  
    {
570  
    {
571  
        std::lock_guard lock(mutex_);
571  
        std::lock_guard lock(mutex_);
572  
        // Already removed by cancel_timer or process_expired
572  
        // Already removed by cancel_timer or process_expired
573  
        if (!w->impl_)
573  
        if (!w->impl_)
574  
            return;
574  
            return;
575  
        auto* impl = w->impl_;
575  
        auto* impl = w->impl_;
576  
        w->impl_   = nullptr;
576  
        w->impl_   = nullptr;
577  
        impl->waiters_.remove(w);
577  
        impl->waiters_.remove(w);
578  
        if (impl->waiters_.empty())
578  
        if (impl->waiters_.empty())
579  
        {
579  
        {
580  
            remove_timer_impl(*impl);
580  
            remove_timer_impl(*impl);
581  
            impl->might_have_pending_waits_ = false;
581  
            impl->might_have_pending_waits_ = false;
582  
        }
582  
        }
583  
        refresh_cached_nearest();
583  
        refresh_cached_nearest();
584  
    }
584  
    }
585  

585  

586  
    w->ec_value_ = make_error_code(capy::error::canceled);
586  
    w->ec_value_ = make_error_code(capy::error::canceled);
587  
    sched_->post(&w->op_);
587  
    sched_->post(&w->op_);
588  
}
588  
}
589  

589  

590  
inline std::size_t
590  
inline std::size_t
591  
timer_service::cancel_one_waiter(implementation& impl)
591  
timer_service::cancel_one_waiter(implementation& impl)
592  
{
592  
{
593  
    if (!impl.might_have_pending_waits_)
593  
    if (!impl.might_have_pending_waits_)
594  
        return 0;
594  
        return 0;
595  

595  

596  
    waiter_node* w = nullptr;
596  
    waiter_node* w = nullptr;
597  

597  

598  
    {
598  
    {
599  
        std::lock_guard lock(mutex_);
599  
        std::lock_guard lock(mutex_);
600  
        w = impl.waiters_.pop_front();
600  
        w = impl.waiters_.pop_front();
601  
        if (!w)
601  
        if (!w)
602  
            return 0;
602  
            return 0;
603  
        w->impl_ = nullptr;
603  
        w->impl_ = nullptr;
604  
        if (impl.waiters_.empty())
604  
        if (impl.waiters_.empty())
605  
        {
605  
        {
606  
            remove_timer_impl(impl);
606  
            remove_timer_impl(impl);
607  
            impl.might_have_pending_waits_ = false;
607  
            impl.might_have_pending_waits_ = false;
608  
        }
608  
        }
609  
        refresh_cached_nearest();
609  
        refresh_cached_nearest();
610  
    }
610  
    }
611  

611  

612  
    w->ec_value_ = make_error_code(capy::error::canceled);
612  
    w->ec_value_ = make_error_code(capy::error::canceled);
613  
    sched_->post(&w->op_);
613  
    sched_->post(&w->op_);
614  
    return 1;
614  
    return 1;
615  
}
615  
}
616  

616  

617  
inline std::size_t
617  
inline std::size_t
618  
timer_service::process_expired()
618  
timer_service::process_expired()
619  
{
619  
{
620  
    intrusive_list<waiter_node> expired;
620  
    intrusive_list<waiter_node> expired;
621  

621  

622  
    {
622  
    {
623  
        std::lock_guard lock(mutex_);
623  
        std::lock_guard lock(mutex_);
624  
        auto now = clock_type::now();
624  
        auto now = clock_type::now();
625  

625  

626  
        while (!heap_.empty() && heap_[0].time_ <= now)
626  
        while (!heap_.empty() && heap_[0].time_ <= now)
627  
        {
627  
        {
628  
            implementation* t = heap_[0].timer_;
628  
            implementation* t = heap_[0].timer_;
629  
            remove_timer_impl(*t);
629  
            remove_timer_impl(*t);
630  
            while (auto* w = t->waiters_.pop_front())
630  
            while (auto* w = t->waiters_.pop_front())
631  
            {
631  
            {
632  
                w->impl_     = nullptr;
632  
                w->impl_     = nullptr;
633  
                w->ec_value_ = {};
633  
                w->ec_value_ = {};
634  
                expired.push_back(w);
634  
                expired.push_back(w);
635  
            }
635  
            }
636  
            t->might_have_pending_waits_ = false;
636  
            t->might_have_pending_waits_ = false;
637  
        }
637  
        }
638  

638  

639  
        refresh_cached_nearest();
639  
        refresh_cached_nearest();
640  
    }
640  
    }
641  

641  

642  
    std::size_t count = 0;
642  
    std::size_t count = 0;
643  
    while (auto* w = expired.pop_front())
643  
    while (auto* w = expired.pop_front())
644  
    {
644  
    {
645  
        sched_->post(&w->op_);
645  
        sched_->post(&w->op_);
646  
        ++count;
646  
        ++count;
647  
    }
647  
    }
648  

648  

649  
    return count;
649  
    return count;
650  
}
650  
}
651  

651  

652  
inline void
652  
inline void
653  
timer_service::remove_timer_impl(implementation& impl)
653  
timer_service::remove_timer_impl(implementation& impl)
654  
{
654  
{
655  
    std::size_t index = impl.heap_index_;
655  
    std::size_t index = impl.heap_index_;
656  
    if (index >= heap_.size())
656  
    if (index >= heap_.size())
657  
        return; // Not in heap
657  
        return; // Not in heap
658  

658  

659  
    if (index == heap_.size() - 1)
659  
    if (index == heap_.size() - 1)
660  
    {
660  
    {
661  
        // Last element, just pop
661  
        // Last element, just pop
662  
        impl.heap_index_ = (std::numeric_limits<std::size_t>::max)();
662  
        impl.heap_index_ = (std::numeric_limits<std::size_t>::max)();
663  
        heap_.pop_back();
663  
        heap_.pop_back();
664  
    }
664  
    }
665  
    else
665  
    else
666  
    {
666  
    {
667  
        // Swap with last and reheapify
667  
        // Swap with last and reheapify
668  
        swap_heap(index, heap_.size() - 1);
668  
        swap_heap(index, heap_.size() - 1);
669  
        impl.heap_index_ = (std::numeric_limits<std::size_t>::max)();
669  
        impl.heap_index_ = (std::numeric_limits<std::size_t>::max)();
670  
        heap_.pop_back();
670  
        heap_.pop_back();
671  

671  

672  
        if (index > 0 && heap_[index].time_ < heap_[(index - 1) / 2].time_)
672  
        if (index > 0 && heap_[index].time_ < heap_[(index - 1) / 2].time_)
673  
            up_heap(index);
673  
            up_heap(index);
674  
        else
674  
        else
675  
            down_heap(index);
675  
            down_heap(index);
676  
    }
676  
    }
677  
}
677  
}
678  

678  

679  
inline void
679  
inline void
680  
timer_service::up_heap(std::size_t index)
680  
timer_service::up_heap(std::size_t index)
681  
{
681  
{
682  
    while (index > 0)
682  
    while (index > 0)
683  
    {
683  
    {
684  
        std::size_t parent = (index - 1) / 2;
684  
        std::size_t parent = (index - 1) / 2;
685  
        if (!(heap_[index].time_ < heap_[parent].time_))
685  
        if (!(heap_[index].time_ < heap_[parent].time_))
686  
            break;
686  
            break;
687  
        swap_heap(index, parent);
687  
        swap_heap(index, parent);
688  
        index = parent;
688  
        index = parent;
689  
    }
689  
    }
690  
}
690  
}
691  

691  

692  
inline void
692  
inline void
693  
timer_service::down_heap(std::size_t index)
693  
timer_service::down_heap(std::size_t index)
694  
{
694  
{
695  
    std::size_t child = index * 2 + 1;
695  
    std::size_t child = index * 2 + 1;
696  
    while (child < heap_.size())
696  
    while (child < heap_.size())
697  
    {
697  
    {
698  
        std::size_t min_child = (child + 1 == heap_.size() ||
698  
        std::size_t min_child = (child + 1 == heap_.size() ||
699  
                                 heap_[child].time_ < heap_[child + 1].time_)
699  
                                 heap_[child].time_ < heap_[child + 1].time_)
700  
            ? child
700  
            ? child
701  
            : child + 1;
701  
            : child + 1;
702  

702  

703  
        if (heap_[index].time_ < heap_[min_child].time_)
703  
        if (heap_[index].time_ < heap_[min_child].time_)
704  
            break;
704  
            break;
705  

705  

706  
        swap_heap(index, min_child);
706  
        swap_heap(index, min_child);
707  
        index = min_child;
707  
        index = min_child;
708  
        child = index * 2 + 1;
708  
        child = index * 2 + 1;
709  
    }
709  
    }
710  
}
710  
}
711  

711  

712  
inline void
712  
inline void
713  
timer_service::swap_heap(std::size_t i1, std::size_t i2)
713  
timer_service::swap_heap(std::size_t i1, std::size_t i2)
714  
{
714  
{
715  
    heap_entry tmp                = heap_[i1];
715  
    heap_entry tmp                = heap_[i1];
716  
    heap_[i1]                     = heap_[i2];
716  
    heap_[i1]                     = heap_[i2];
717  
    heap_[i2]                     = tmp;
717  
    heap_[i2]                     = tmp;
718  
    heap_[i1].timer_->heap_index_ = i1;
718  
    heap_[i1].timer_->heap_index_ = i1;
719  
    heap_[i2].timer_->heap_index_ = i2;
719  
    heap_[i2].timer_->heap_index_ = i2;
720  
}
720  
}
721  

721  

722  
// waiter_node out-of-class member function definitions
722  
// waiter_node out-of-class member function definitions
723  

723  

724  
inline void
724  
inline void
725  
waiter_node::canceller::operator()() const
725  
waiter_node::canceller::operator()() const
726  
{
726  
{
727  
    waiter_->svc_->cancel_waiter(waiter_);
727  
    waiter_->svc_->cancel_waiter(waiter_);
728  
}
728  
}
729  

729  

730  
inline void
730  
inline void
731  
waiter_node::completion_op::do_complete(
731  
waiter_node::completion_op::do_complete(
732  
    [[maybe_unused]] void* owner, scheduler_op* base, std::uint32_t, std::uint32_t)
732  
    [[maybe_unused]] void* owner, scheduler_op* base, std::uint32_t, std::uint32_t)
733  
{
733  
{
734  
    // owner is always non-null here. The destroy path (owner == nullptr)
734  
    // owner is always non-null here. The destroy path (owner == nullptr)
735  
    // is unreachable because completion_op overrides destroy() directly,
735  
    // is unreachable because completion_op overrides destroy() directly,
736  
    // bypassing scheduler_op::destroy() which would call func_(nullptr, ...).
736  
    // bypassing scheduler_op::destroy() which would call func_(nullptr, ...).
737  
    BOOST_COROSIO_ASSERT(owner);
737  
    BOOST_COROSIO_ASSERT(owner);
738  
    static_cast<completion_op*>(base)->operator()();
738  
    static_cast<completion_op*>(base)->operator()();
739  
}
739  
}
740  

740  

741  
inline void
741  
inline void
742  
waiter_node::completion_op::operator()()
742  
waiter_node::completion_op::operator()()
743  
{
743  
{
744  
    auto* w = waiter_;
744  
    auto* w = waiter_;
745  
    w->stop_cb_.reset();
745  
    w->stop_cb_.reset();
746  
    if (w->ec_out_)
746  
    if (w->ec_out_)
747  
        *w->ec_out_ = w->ec_value_;
747  
        *w->ec_out_ = w->ec_value_;
748  

748  

749  
    auto h      = w->h_;
749  
    auto h      = w->h_;
750  
    auto d      = w->d_;
750  
    auto d      = w->d_;
751  
    auto* svc   = w->svc_;
751  
    auto* svc   = w->svc_;
752  
    auto& sched = svc->get_scheduler();
752  
    auto& sched = svc->get_scheduler();
753  

753  

754  
    svc->destroy_waiter(w);
754  
    svc->destroy_waiter(w);
755  

755  

756  
    d.post(h);
756  
    d.post(h);
757  
    sched.work_finished();
757  
    sched.work_finished();
758  
}
758  
}
759  

759  

760  
inline void
760  
inline void
761  
waiter_node::completion_op::destroy()
761  
waiter_node::completion_op::destroy()
762  
{
762  
{
763  
    // Called during scheduler shutdown drain when this completion_op is
763  
    // Called during scheduler shutdown drain when this completion_op is
764  
    // in the scheduler's ready queue (posted by cancel_timer() or
764  
    // in the scheduler's ready queue (posted by cancel_timer() or
765  
    // process_expired()). Balances the work_started() from
765  
    // process_expired()). Balances the work_started() from
766  
    // implementation::wait(). The scheduler drain loop separately
766  
    // implementation::wait(). The scheduler drain loop separately
767  
    // balances the work_started() from post(). On IOCP both decrements
767  
    // balances the work_started() from post(). On IOCP both decrements
768  
    // are required for outstanding_work_ to reach zero; on other
768  
    // are required for outstanding_work_ to reach zero; on other
769  
    // backends this is harmless.
769  
    // backends this is harmless.
770  
    //
770  
    //
771  
    // This override also prevents scheduler_op::destroy() from calling
771  
    // This override also prevents scheduler_op::destroy() from calling
772  
    // do_complete(nullptr, ...). See also: timer_service::shutdown()
772  
    // do_complete(nullptr, ...). See also: timer_service::shutdown()
773  
    // which drains waiters still in the timer heap (the other path).
773  
    // which drains waiters still in the timer heap (the other path).
774  
    auto* w = waiter_;
774  
    auto* w = waiter_;
775  
    w->stop_cb_.reset();
775  
    w->stop_cb_.reset();
776  
    auto h = std::exchange(w->h_, {});
776  
    auto h = std::exchange(w->h_, {});
777  
    auto& sched = w->svc_->get_scheduler();
777  
    auto& sched = w->svc_->get_scheduler();
778  
    delete w;
778  
    delete w;
779  
    sched.work_finished();
779  
    sched.work_finished();
780  
    if (h)
780  
    if (h)
781  
        h.destroy();
781  
        h.destroy();
782  
}
782  
}
783  

783  

784  
inline std::coroutine_handle<>
784  
inline std::coroutine_handle<>
785  
timer_service::implementation::wait(
785  
timer_service::implementation::wait(
786  
    std::coroutine_handle<> h,
786  
    std::coroutine_handle<> h,
787  
    capy::executor_ref d,
787  
    capy::executor_ref d,
788  
    std::stop_token token,
788  
    std::stop_token token,
789  
    std::error_code* ec)
789  
    std::error_code* ec)
790  
{
790  
{
791  
    // Already-expired fast path — no waiter_node, no mutex.
791  
    // Already-expired fast path — no waiter_node, no mutex.
792  
    // Post instead of dispatch so the coroutine yields to the
792  
    // Post instead of dispatch so the coroutine yields to the
793  
    // scheduler, allowing other queued work to run.
793  
    // scheduler, allowing other queued work to run.
794  
    if (heap_index_ == (std::numeric_limits<std::size_t>::max)())
794  
    if (heap_index_ == (std::numeric_limits<std::size_t>::max)())
795  
    {
795  
    {
796  
        if (expiry_ == (time_point::min)() || expiry_ <= clock_type::now())
796  
        if (expiry_ == (time_point::min)() || expiry_ <= clock_type::now())
797  
        {
797  
        {
798  
            if (ec)
798  
            if (ec)
799  
                *ec = {};
799  
                *ec = {};
800  
            d.post(h);
800  
            d.post(h);
801  
            return std::noop_coroutine();
801  
            return std::noop_coroutine();
802  
        }
802  
        }
803  
    }
803  
    }
804  

804  

805  
    auto* w    = svc_->create_waiter();
805  
    auto* w    = svc_->create_waiter();
806  
    w->impl_   = this;
806  
    w->impl_   = this;
807  
    w->svc_    = svc_;
807  
    w->svc_    = svc_;
808  
    w->h_      = h;
808  
    w->h_      = h;
809  
    w->d_      = d;
809  
    w->d_      = d;
810  
    w->token_  = std::move(token);
810  
    w->token_  = std::move(token);
811  
    w->ec_out_ = ec;
811  
    w->ec_out_ = ec;
812  

812  

813  
    svc_->insert_waiter(*this, w);
813  
    svc_->insert_waiter(*this, w);
814  
    might_have_pending_waits_ = true;
814  
    might_have_pending_waits_ = true;
815  
    svc_->get_scheduler().work_started();
815  
    svc_->get_scheduler().work_started();
816  

816  

817  
    if (w->token_.stop_possible())
817  
    if (w->token_.stop_possible())
818  
        w->stop_cb_.emplace(w->token_, waiter_node::canceller{w});
818  
        w->stop_cb_.emplace(w->token_, waiter_node::canceller{w});
819  

819  

820  
    return std::noop_coroutine();
820  
    return std::noop_coroutine();
821  
}
821  
}
822  

822  

823  
// Free functions
823  
// Free functions
824  

824  

825  
struct timer_service_access
825  
struct timer_service_access
826  
{
826  
{
827  
    static native_scheduler& get_scheduler(io_context& ctx) noexcept
827  
    static native_scheduler& get_scheduler(io_context& ctx) noexcept
828  
    {
828  
    {
829  
        return static_cast<native_scheduler&>(*ctx.sched_);
829  
        return static_cast<native_scheduler&>(*ctx.sched_);
830  
    }
830  
    }
831  
};
831  
};
832  

832  

833  
// Bypass find_service() mutex by reading the scheduler's cached pointer
833  
// Bypass find_service() mutex by reading the scheduler's cached pointer
834  
inline io_object::io_service&
834  
inline io_object::io_service&
835  
timer_service_direct(capy::execution_context& ctx) noexcept
835  
timer_service_direct(capy::execution_context& ctx) noexcept
836  
{
836  
{
837  
    return *timer_service_access::get_scheduler(static_cast<io_context&>(ctx))
837  
    return *timer_service_access::get_scheduler(static_cast<io_context&>(ctx))
838  
                .timer_svc_;
838  
                .timer_svc_;
839  
}
839  
}
840  

840  

841  
inline std::size_t
841  
inline std::size_t
842  
timer_service_update_expiry(timer::implementation& base)
842  
timer_service_update_expiry(timer::implementation& base)
843  
{
843  
{
844  
    auto& impl = static_cast<timer_service::implementation&>(base);
844  
    auto& impl = static_cast<timer_service::implementation&>(base);
845  
    return impl.svc_->update_timer(impl, impl.expiry_);
845  
    return impl.svc_->update_timer(impl, impl.expiry_);
846  
}
846  
}
847  

847  

848  
inline std::size_t
848  
inline std::size_t
849  
timer_service_cancel(timer::implementation& base) noexcept
849  
timer_service_cancel(timer::implementation& base) noexcept
850  
{
850  
{
851  
    auto& impl = static_cast<timer_service::implementation&>(base);
851  
    auto& impl = static_cast<timer_service::implementation&>(base);
852  
    return impl.svc_->cancel_timer(impl);
852  
    return impl.svc_->cancel_timer(impl);
853  
}
853  
}
854  

854  

855  
inline std::size_t
855  
inline std::size_t
856  
timer_service_cancel_one(timer::implementation& base) noexcept
856  
timer_service_cancel_one(timer::implementation& base) noexcept
857  
{
857  
{
858  
    auto& impl = static_cast<timer_service::implementation&>(base);
858  
    auto& impl = static_cast<timer_service::implementation&>(base);
859  
    return impl.svc_->cancel_one_waiter(impl);
859  
    return impl.svc_->cancel_one_waiter(impl);
860  
}
860  
}
861  

861  

862  
inline timer_service&
862  
inline timer_service&
863  
get_timer_service(capy::execution_context& ctx, scheduler& sched)
863  
get_timer_service(capy::execution_context& ctx, scheduler& sched)
864  
{
864  
{
865  
    return ctx.make_service<timer_service>(sched);
865  
    return ctx.make_service<timer_service>(sched);
866  
}
866  
}
867  

867  

868  
} // namespace boost::corosio::detail
868  
} // namespace boost::corosio::detail
869  

869  

870  
#endif
870  
#endif