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/detail/intrusive.hpp>
18  
#include <boost/corosio/detail/intrusive.hpp>
18  
#include <boost/corosio/detail/thread_local_ptr.hpp>
19  
#include <boost/corosio/detail/thread_local_ptr.hpp>
19  
#include <boost/capy/error.hpp>
20  
#include <boost/capy/error.hpp>
20  
#include <boost/capy/ex/execution_context.hpp>
21  
#include <boost/capy/ex/execution_context.hpp>
21  
#include <boost/capy/ex/executor_ref.hpp>
22  
#include <boost/capy/ex/executor_ref.hpp>
22  
#include <system_error>
23  
#include <system_error>
23  

24  

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

35  

35  
namespace boost::corosio::detail {
36  
namespace boost::corosio::detail {
36  

37  

37  
struct scheduler;
38  
struct scheduler;
38  

39  

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

43  

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

49  

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

53  

53  
    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
54  
    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
55  
    heap is ordered by expiry time; the scheduler queries
56  
    heap is ordered by expiry time; the scheduler queries
56  
    nearest_expiry() to set the epoll/timerfd timeout.
57  
    nearest_expiry() to set the epoll/timerfd timeout.
57  

58  

58  
    Optimization Strategy
59  
    Optimization Strategy
59  
    ---------------------
60  
    ---------------------
60  
    1. Deferred heap insertion — expires_after() stores the expiry
61  
    1. Deferred heap insertion — expires_after() stores the expiry
61  
       but does not insert into the heap. Insertion happens in wait().
62  
       but does not insert into the heap. Insertion happens in wait().
62  
    2. Thread-local impl cache — single-slot per-thread cache.
63  
    2. Thread-local impl cache — single-slot per-thread cache.
63  
    3. Embedded completion_op — eliminates heap allocation per fire/cancel.
64  
    3. Embedded completion_op — eliminates heap allocation per fire/cancel.
64  
    4. Cached nearest expiry — atomic avoids mutex in nearest_expiry().
65  
    4. Cached nearest expiry — atomic avoids mutex in nearest_expiry().
65  
    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.
66  
    6. Thread-local waiter cache — single-slot per-thread cache.
67  
    6. Thread-local waiter cache — single-slot per-thread cache.
67  

68  

68  
    Concurrency
69  
    Concurrency
69  
    -----------
70  
    -----------
70  
    stop_token callbacks can fire from any thread. The impl_
71  
    stop_token callbacks can fire from any thread. The impl_
71  
    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.
72  
*/
73  
*/
73  

74  

74  
struct BOOST_COROSIO_SYMBOL_VISIBLE waiter_node;
75  
struct BOOST_COROSIO_SYMBOL_VISIBLE waiter_node;
75  

76  

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

78  

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

88  

88  
    /// Type-erased callback for earliest-expiry-changed notifications.
89  
    /// Type-erased callback for earliest-expiry-changed notifications.
89  
    class callback
90  
    class callback
90  
    {
91  
    {
91  
        void* ctx_         = nullptr;
92  
        void* ctx_         = nullptr;
92  
        void (*fn_)(void*) = nullptr;
93  
        void (*fn_)(void*) = nullptr;
93  

94  

94  
    public:
95  
    public:
95  
        /// Construct an empty callback.
96  
        /// Construct an empty callback.
96  
        callback() = default;
97  
        callback() = default;
97  

98  

98  
        /// Construct a callback with the given context and function.
99  
        /// Construct a callback with the given context and function.
99  
        callback(void* ctx, void (*fn)(void*)) noexcept : ctx_(ctx), fn_(fn) {}
100  
        callback(void* ctx, void (*fn)(void*)) noexcept : ctx_(ctx), fn_(fn) {}
100  

101  

101  
        /// Return true if the callback is non-empty.
102  
        /// Return true if the callback is non-empty.
102  
        explicit operator bool() const noexcept
103  
        explicit operator bool() const noexcept
103  
        {
104  
        {
104  
            return fn_ != nullptr;
105  
            return fn_ != nullptr;
105  
        }
106  
        }
106  

107  

107  
        /// Invoke the callback.
108  
        /// Invoke the callback.
108  
        void operator()() const
109  
        void operator()() const
109  
        {
110  
        {
110  
            if (fn_)
111  
            if (fn_)
111  
                fn_(ctx_);
112  
                fn_(ctx_);
112  
        }
113  
        }
113  
    };
114  
    };
114  

115  

115  
    struct implementation;
116  
    struct implementation;
116  

117  

117  
private:
118  
private:
118  
    struct heap_entry
119  
    struct heap_entry
119  
    {
120  
    {
120  
        time_point time_;
121  
        time_point time_;
121  
        implementation* timer_;
122  
        implementation* timer_;
122  
    };
123  
    };
123  

124  

124  
    scheduler* sched_ = nullptr;
125  
    scheduler* sched_ = nullptr;
125  
    mutable std::mutex mutex_;
126  
    mutable std::mutex mutex_;
126  
    std::vector<heap_entry> heap_;
127  
    std::vector<heap_entry> heap_;
127  
    implementation* free_list_     = nullptr;
128  
    implementation* free_list_     = nullptr;
128  
    waiter_node* waiter_free_list_ = nullptr;
129  
    waiter_node* waiter_free_list_ = nullptr;
129  
    callback on_earliest_changed_;
130  
    callback on_earliest_changed_;
130  
    bool shutting_down_ = false;
131  
    bool shutting_down_ = false;
131  
    // Avoids mutex in nearest_expiry() and empty()
132  
    // Avoids mutex in nearest_expiry() and empty()
132  
    mutable std::atomic<std::int64_t> cached_nearest_ns_{
133  
    mutable std::atomic<std::int64_t> cached_nearest_ns_{
133  
        (std::numeric_limits<std::int64_t>::max)()};
134  
        (std::numeric_limits<std::int64_t>::max)()};
134  

135  

135  
public:
136  
public:
136  
    /// Construct the timer service bound to a scheduler.
137  
    /// Construct the timer service bound to a scheduler.
137  
    inline timer_service(capy::execution_context&, scheduler& sched)
138  
    inline timer_service(capy::execution_context&, scheduler& sched)
138  
        : sched_(&sched)
139  
        : sched_(&sched)
139  
    {
140  
    {
140  
    }
141  
    }
141  

142  

142  
    /// Return the associated scheduler.
143  
    /// Return the associated scheduler.
143  
    inline scheduler& get_scheduler() noexcept
144  
    inline scheduler& get_scheduler() noexcept
144  
    {
145  
    {
145  
        return *sched_;
146  
        return *sched_;
146  
    }
147  
    }
147  

148  

148  
    /// Destroy the timer service.
149  
    /// Destroy the timer service.
149  
    ~timer_service() override = default;
150  
    ~timer_service() override = default;
150  

151  

151  
    timer_service(timer_service const&)            = delete;
152  
    timer_service(timer_service const&)            = delete;
152  
    timer_service& operator=(timer_service const&) = delete;
153  
    timer_service& operator=(timer_service const&) = delete;
153  

154  

154  
    /// Register a callback invoked when the earliest expiry changes.
155  
    /// Register a callback invoked when the earliest expiry changes.
155  
    inline void set_on_earliest_changed(callback cb)
156  
    inline void set_on_earliest_changed(callback cb)
156  
    {
157  
    {
157  
        on_earliest_changed_ = cb;
158  
        on_earliest_changed_ = cb;
158  
    }
159  
    }
159  

160  

160  
    /// Return true if no timers are in the heap.
161  
    /// Return true if no timers are in the heap.
161  
    inline bool empty() const noexcept
162  
    inline bool empty() const noexcept
162  
    {
163  
    {
163  
        return cached_nearest_ns_.load(std::memory_order_acquire) ==
164  
        return cached_nearest_ns_.load(std::memory_order_acquire) ==
164  
            (std::numeric_limits<std::int64_t>::max)();
165  
            (std::numeric_limits<std::int64_t>::max)();
165  
    }
166  
    }
166  

167  

167  
    /// Return the nearest timer expiry without acquiring the mutex.
168  
    /// Return the nearest timer expiry without acquiring the mutex.
168  
    inline time_point nearest_expiry() const noexcept
169  
    inline time_point nearest_expiry() const noexcept
169  
    {
170  
    {
170  
        auto ns = cached_nearest_ns_.load(std::memory_order_acquire);
171  
        auto ns = cached_nearest_ns_.load(std::memory_order_acquire);
171  
        return time_point(time_point::duration(ns));
172  
        return time_point(time_point::duration(ns));
172  
    }
173  
    }
173  

174  

174  
    /// Cancel all pending timers and free cached resources.
175  
    /// Cancel all pending timers and free cached resources.
175  
    inline void shutdown() override;
176  
    inline void shutdown() override;
176  

177  

177  
    /// Construct a new timer implementation.
178  
    /// Construct a new timer implementation.
178  
    inline io_object::implementation* construct() override;
179  
    inline io_object::implementation* construct() override;
179  

180  

180  
    /// Destroy a timer implementation, cancelling pending waiters.
181  
    /// Destroy a timer implementation, cancelling pending waiters.
181  
    inline void destroy(io_object::implementation* p) override;
182  
    inline void destroy(io_object::implementation* p) override;
182  

183  

183  
    /// Cancel and recycle a timer implementation.
184  
    /// Cancel and recycle a timer implementation.
184  
    inline void destroy_impl(implementation& impl);
185  
    inline void destroy_impl(implementation& impl);
185  

186  

186  
    /// Create or recycle a waiter node.
187  
    /// Create or recycle a waiter node.
187  
    inline waiter_node* create_waiter();
188  
    inline waiter_node* create_waiter();
188  

189  

189  
    /// Return a waiter node to the cache or free list.
190  
    /// Return a waiter node to the cache or free list.
190  
    inline void destroy_waiter(waiter_node* w);
191  
    inline void destroy_waiter(waiter_node* w);
191  

192  

192  
    /// Update the timer expiry, cancelling existing waiters.
193  
    /// Update the timer expiry, cancelling existing waiters.
193  
    inline std::size_t update_timer(implementation& impl, time_point new_time);
194  
    inline std::size_t update_timer(implementation& impl, time_point new_time);
194  

195  

195  
    /// Insert a waiter into the timer's waiter list and the heap.
196  
    /// Insert a waiter into the timer's waiter list and the heap.
196  
    inline void insert_waiter(implementation& impl, waiter_node* w);
197  
    inline void insert_waiter(implementation& impl, waiter_node* w);
197  

198  

198  
    /// Cancel all waiters on a timer.
199  
    /// Cancel all waiters on a timer.
199  
    inline std::size_t cancel_timer(implementation& impl);
200  
    inline std::size_t cancel_timer(implementation& impl);
200  

201  

201  
    /// Cancel a single waiter ( stop_token callback path ).
202  
    /// Cancel a single waiter ( stop_token callback path ).
202  
    inline void cancel_waiter(waiter_node* w);
203  
    inline void cancel_waiter(waiter_node* w);
203  

204  

204  
    /// Cancel one waiter on a timer.
205  
    /// Cancel one waiter on a timer.
205  
    inline std::size_t cancel_one_waiter(implementation& impl);
206  
    inline std::size_t cancel_one_waiter(implementation& impl);
206  

207  

207  
    /// Complete all waiters whose timers have expired.
208  
    /// Complete all waiters whose timers have expired.
208  
    inline std::size_t process_expired();
209  
    inline std::size_t process_expired();
209  

210  

210  
private:
211  
private:
211  
    inline void refresh_cached_nearest() noexcept
212  
    inline void refresh_cached_nearest() noexcept
212  
    {
213  
    {
213  
        auto ns = heap_.empty() ? (std::numeric_limits<std::int64_t>::max)()
214  
        auto ns = heap_.empty() ? (std::numeric_limits<std::int64_t>::max)()
214  
                                : heap_[0].time_.time_since_epoch().count();
215  
                                : heap_[0].time_.time_since_epoch().count();
215  
        cached_nearest_ns_.store(ns, std::memory_order_release);
216  
        cached_nearest_ns_.store(ns, std::memory_order_release);
216  
    }
217  
    }
217  

218  

218  
    inline void remove_timer_impl(implementation& impl);
219  
    inline void remove_timer_impl(implementation& impl);
219  
    inline void up_heap(std::size_t index);
220  
    inline void up_heap(std::size_t index);
220  
    inline void down_heap(std::size_t index);
221  
    inline void down_heap(std::size_t index);
221  
    inline void swap_heap(std::size_t i1, std::size_t i2);
222  
    inline void swap_heap(std::size_t i1, std::size_t i2);
222  
};
223  
};
223  

224  

224  
struct BOOST_COROSIO_SYMBOL_VISIBLE waiter_node
225  
struct BOOST_COROSIO_SYMBOL_VISIBLE waiter_node
225  
    : intrusive_list<waiter_node>::node
226  
    : intrusive_list<waiter_node>::node
226  
{
227  
{
227  
    // Embedded completion op — avoids heap allocation per fire/cancel
228  
    // Embedded completion op — avoids heap allocation per fire/cancel
228  
    struct completion_op final : scheduler_op
229  
    struct completion_op final : scheduler_op
229  
    {
230  
    {
230  
        waiter_node* waiter_ = nullptr;
231  
        waiter_node* waiter_ = nullptr;
231  

232  

232  
        static void do_complete(
233  
        static void do_complete(
233  
            void* owner, scheduler_op* base, std::uint32_t, std::uint32_t);
234  
            void* owner, scheduler_op* base, std::uint32_t, std::uint32_t);
234  

235  

235  
        completion_op() noexcept : scheduler_op(&do_complete) {}
236  
        completion_op() noexcept : scheduler_op(&do_complete) {}
236  

237  

237  
        void operator()() override;
238  
        void operator()() override;
238  
        void destroy() override;
239  
        void destroy() override;
239  
    };
240  
    };
240  

241  

241  
    // Per-waiter stop_token cancellation
242  
    // Per-waiter stop_token cancellation
242  
    struct canceller
243  
    struct canceller
243  
    {
244  
    {
244  
        waiter_node* waiter_;
245  
        waiter_node* waiter_;
245  
        void operator()() const;
246  
        void operator()() const;
246  
    };
247  
    };
247  

248  

248  
    // nullptr once removed from timer's waiter list (concurrency marker)
249  
    // nullptr once removed from timer's waiter list (concurrency marker)
249  
    timer_service::implementation* impl_ = nullptr;
250  
    timer_service::implementation* impl_ = nullptr;
250  
    timer_service* svc_                  = nullptr;
251  
    timer_service* svc_                  = nullptr;
251  
    std::coroutine_handle<> h_;
252  
    std::coroutine_handle<> h_;
252  
    capy::continuation* cont_            = nullptr;
253  
    capy::continuation* cont_            = nullptr;
253  
    capy::executor_ref d_;
254  
    capy::executor_ref d_;
254  
    std::error_code* ec_out_ = nullptr;
255  
    std::error_code* ec_out_ = nullptr;
255  
    std::stop_token token_;
256  
    std::stop_token token_;
256  
    std::optional<std::stop_callback<canceller>> stop_cb_;
257  
    std::optional<std::stop_callback<canceller>> stop_cb_;
257  
    completion_op op_;
258  
    completion_op op_;
258  
    std::error_code ec_value_;
259  
    std::error_code ec_value_;
259  
    waiter_node* next_free_ = nullptr;
260  
    waiter_node* next_free_ = nullptr;
260  

261  

261  
    waiter_node() noexcept
262  
    waiter_node() noexcept
262  
    {
263  
    {
263  
        op_.waiter_ = this;
264  
        op_.waiter_ = this;
264  
    }
265  
    }
265  
};
266  
};
266  

267  

267  
struct timer_service::implementation final : timer::implementation
268  
struct timer_service::implementation final : timer::implementation
268  
{
269  
{
269  
    using clock_type = std::chrono::steady_clock;
270  
    using clock_type = std::chrono::steady_clock;
270  
    using time_point = clock_type::time_point;
271  
    using time_point = clock_type::time_point;
271  
    using duration   = clock_type::duration;
272  
    using duration   = clock_type::duration;
272  

273  

273  
    timer_service* svc_ = nullptr;
274  
    timer_service* svc_ = nullptr;
274  
    intrusive_list<waiter_node> waiters_;
275  
    intrusive_list<waiter_node> waiters_;
275  

276  

276  
    // Free list linkage (reused when impl is on free_list)
277  
    // Free list linkage (reused when impl is on free_list)
277  
    implementation* next_free_ = nullptr;
278  
    implementation* next_free_ = nullptr;
278  

279  

279  
    inline explicit implementation(timer_service& svc) noexcept;
280  
    inline explicit implementation(timer_service& svc) noexcept;
280  

281  

281  
    inline std::coroutine_handle<> wait(
282  
    inline std::coroutine_handle<> wait(
282  
        std::coroutine_handle<>,
283  
        std::coroutine_handle<>,
283  
        capy::executor_ref,
284  
        capy::executor_ref,
284  
        std::stop_token,
285  
        std::stop_token,
285  
        std::error_code*,
286  
        std::error_code*,
286  
        capy::continuation*) override;
287  
        capy::continuation*) override;
287  
};
288  
};
288  

289  

289  
// Thread-local caches avoid hot-path mutex acquisitions:
290  
// Thread-local caches avoid hot-path mutex acquisitions:
290  
// 1. Impl cache — single-slot, validated by comparing svc_
291  
// 1. Impl cache — single-slot, validated by comparing svc_
291  
// 2. Waiter cache — single-slot, no service affinity
292  
// 2. Waiter cache — single-slot, no service affinity
292  
// All caches are cleared by timer_service_invalidate_cache() during shutdown.
293  
// All caches are cleared by timer_service_invalidate_cache() during shutdown.
293  

294  

294  
inline thread_local_ptr<timer_service::implementation> tl_cached_impl;
295  
inline thread_local_ptr<timer_service::implementation> tl_cached_impl;
295  
inline thread_local_ptr<waiter_node> tl_cached_waiter;
296  
inline thread_local_ptr<waiter_node> tl_cached_waiter;
296  

297  

297  
inline timer_service::implementation*
298  
inline timer_service::implementation*
298  
try_pop_tl_cache(timer_service* svc) noexcept
299  
try_pop_tl_cache(timer_service* svc) noexcept
299  
{
300  
{
300  
    auto* impl = tl_cached_impl.get();
301  
    auto* impl = tl_cached_impl.get();
301  
    if (impl)
302  
    if (impl)
302  
    {
303  
    {
303  
        tl_cached_impl.set(nullptr);
304  
        tl_cached_impl.set(nullptr);
304  
        if (impl->svc_ == svc)
305  
        if (impl->svc_ == svc)
305  
            return impl;
306  
            return impl;
306  
        // Stale impl from a destroyed service
307  
        // Stale impl from a destroyed service
307  
        delete impl;
308  
        delete impl;
308  
    }
309  
    }
309  
    return nullptr;
310  
    return nullptr;
310  
}
311  
}
311  

312  

312  
inline bool
313  
inline bool
313  
try_push_tl_cache(timer_service::implementation* impl) noexcept
314  
try_push_tl_cache(timer_service::implementation* impl) noexcept
314  
{
315  
{
315  
    if (!tl_cached_impl.get())
316  
    if (!tl_cached_impl.get())
316  
    {
317  
    {
317  
        tl_cached_impl.set(impl);
318  
        tl_cached_impl.set(impl);
318  
        return true;
319  
        return true;
319  
    }
320  
    }
320  
    return false;
321  
    return false;
321  
}
322  
}
322  

323  

323  
inline waiter_node*
324  
inline waiter_node*
324  
try_pop_waiter_tl_cache() noexcept
325  
try_pop_waiter_tl_cache() noexcept
325  
{
326  
{
326  
    auto* w = tl_cached_waiter.get();
327  
    auto* w = tl_cached_waiter.get();
327  
    if (w)
328  
    if (w)
328  
    {
329  
    {
329  
        tl_cached_waiter.set(nullptr);
330  
        tl_cached_waiter.set(nullptr);
330  
        return w;
331  
        return w;
331  
    }
332  
    }
332  
    return nullptr;
333  
    return nullptr;
333  
}
334  
}
334  

335  

335  
inline bool
336  
inline bool
336  
try_push_waiter_tl_cache(waiter_node* w) noexcept
337  
try_push_waiter_tl_cache(waiter_node* w) noexcept
337  
{
338  
{
338  
    if (!tl_cached_waiter.get())
339  
    if (!tl_cached_waiter.get())
339  
    {
340  
    {
340  
        tl_cached_waiter.set(w);
341  
        tl_cached_waiter.set(w);
341  
        return true;
342  
        return true;
342  
    }
343  
    }
343  
    return false;
344  
    return false;
344  
}
345  
}
345  

346  

346  
inline void
347  
inline void
347  
timer_service_invalidate_cache() noexcept
348  
timer_service_invalidate_cache() noexcept
348  
{
349  
{
349  
    delete tl_cached_impl.get();
350  
    delete tl_cached_impl.get();
350  
    tl_cached_impl.set(nullptr);
351  
    tl_cached_impl.set(nullptr);
351  

352  

352  
    delete tl_cached_waiter.get();
353  
    delete tl_cached_waiter.get();
353  
    tl_cached_waiter.set(nullptr);
354  
    tl_cached_waiter.set(nullptr);
354  
}
355  
}
355  

356  

356  
// timer_service out-of-class member function definitions
357  
// timer_service out-of-class member function definitions
357  

358  

358  
inline timer_service::implementation::implementation(
359  
inline timer_service::implementation::implementation(
359  
    timer_service& svc) noexcept
360  
    timer_service& svc) noexcept
360  
    : svc_(&svc)
361  
    : svc_(&svc)
361  
{
362  
{
362  
}
363  
}
363  

364  

364  
inline void
365  
inline void
365  
timer_service::shutdown()
366  
timer_service::shutdown()
366  
{
367  
{
367  
    timer_service_invalidate_cache();
368  
    timer_service_invalidate_cache();
368  
    shutting_down_ = true;
369  
    shutting_down_ = true;
369  

370  

370  
    // Snapshot impls and detach them from the heap so that
371  
    // Snapshot impls and detach them from the heap so that
371  
    // coroutine-owned timer destructors (triggered by h.destroy()
372  
    // coroutine-owned timer destructors (triggered by h.destroy()
372  
    // below) cannot re-enter remove_timer_impl() and mutate the
373  
    // below) cannot re-enter remove_timer_impl() and mutate the
373  
    // vector during iteration.
374  
    // vector during iteration.
374  
    std::vector<implementation*> impls;
375  
    std::vector<implementation*> impls;
375  
    impls.reserve(heap_.size());
376  
    impls.reserve(heap_.size());
376  
    for (auto& entry : heap_)
377  
    for (auto& entry : heap_)
377  
    {
378  
    {
378  
        entry.timer_->heap_index_ = (std::numeric_limits<std::size_t>::max)();
379  
        entry.timer_->heap_index_ = (std::numeric_limits<std::size_t>::max)();
379  
        impls.push_back(entry.timer_);
380  
        impls.push_back(entry.timer_);
380  
    }
381  
    }
381  
    heap_.clear();
382  
    heap_.clear();
382  
    cached_nearest_ns_.store(
383  
    cached_nearest_ns_.store(
383  
        (std::numeric_limits<std::int64_t>::max)(), std::memory_order_release);
384  
        (std::numeric_limits<std::int64_t>::max)(), std::memory_order_release);
384  

385  

385  
    // Cancel waiting timers. Each waiter called work_started()
386  
    // Cancel waiting timers. Each waiter called work_started()
386  
    // in implementation::wait(). On IOCP the scheduler shutdown
387  
    // in implementation::wait(). On IOCP the scheduler shutdown
387  
    // loop exits when outstanding_work_ reaches zero, so we must
388  
    // loop exits when outstanding_work_ reaches zero, so we must
388  
    // call work_finished() here to balance it. On other backends
389  
    // call work_finished() here to balance it. On other backends
389  
    // this is harmless.
390  
    // this is harmless.
390  
    for (auto* impl : impls)
391  
    for (auto* impl : impls)
391  
    {
392  
    {
392  
        while (auto* w = impl->waiters_.pop_front())
393  
        while (auto* w = impl->waiters_.pop_front())
393  
        {
394  
        {
394  
            w->stop_cb_.reset();
395  
            w->stop_cb_.reset();
395  
            auto h = std::exchange(w->h_, {});
396  
            auto h = std::exchange(w->h_, {});
396  
            sched_->work_finished();
397  
            sched_->work_finished();
397  
            if (h)
398  
            if (h)
398  
                h.destroy();
399  
                h.destroy();
399  
            delete w;
400  
            delete w;
400  
        }
401  
        }
401  
        delete impl;
402  
        delete impl;
402  
    }
403  
    }
403  

404  

404  
    // Delete free-listed impls
405  
    // Delete free-listed impls
405  
    while (free_list_)
406  
    while (free_list_)
406  
    {
407  
    {
407  
        auto* next = free_list_->next_free_;
408  
        auto* next = free_list_->next_free_;
408  
        delete free_list_;
409  
        delete free_list_;
409  
        free_list_ = next;
410  
        free_list_ = next;
410  
    }
411  
    }
411  

412  

412  
    // Delete free-listed waiters
413  
    // Delete free-listed waiters
413  
    while (waiter_free_list_)
414  
    while (waiter_free_list_)
414  
    {
415  
    {
415  
        auto* next = waiter_free_list_->next_free_;
416  
        auto* next = waiter_free_list_->next_free_;
416  
        delete waiter_free_list_;
417  
        delete waiter_free_list_;
417  
        waiter_free_list_ = next;
418  
        waiter_free_list_ = next;
418  
    }
419  
    }
419  
}
420  
}
420  

421  

421  
inline io_object::implementation*
422  
inline io_object::implementation*
422  
timer_service::construct()
423  
timer_service::construct()
423  
{
424  
{
424  
    implementation* impl = try_pop_tl_cache(this);
425  
    implementation* impl = try_pop_tl_cache(this);
425  
    if (impl)
426  
    if (impl)
426  
    {
427  
    {
427  
        impl->svc_        = this;
428  
        impl->svc_        = this;
428  
        impl->heap_index_ = (std::numeric_limits<std::size_t>::max)();
429  
        impl->heap_index_ = (std::numeric_limits<std::size_t>::max)();
429  
        impl->might_have_pending_waits_ = false;
430  
        impl->might_have_pending_waits_ = false;
430  
        return impl;
431  
        return impl;
431  
    }
432  
    }
432  

433  

433  
    std::lock_guard lock(mutex_);
434  
    std::lock_guard lock(mutex_);
434  
    if (free_list_)
435  
    if (free_list_)
435  
    {
436  
    {
436  
        impl              = free_list_;
437  
        impl              = free_list_;
437  
        free_list_        = impl->next_free_;
438  
        free_list_        = impl->next_free_;
438  
        impl->next_free_  = nullptr;
439  
        impl->next_free_  = nullptr;
439  
        impl->svc_        = this;
440  
        impl->svc_        = this;
440  
        impl->heap_index_ = (std::numeric_limits<std::size_t>::max)();
441  
        impl->heap_index_ = (std::numeric_limits<std::size_t>::max)();
441  
        impl->might_have_pending_waits_ = false;
442  
        impl->might_have_pending_waits_ = false;
442  
    }
443  
    }
443  
    else
444  
    else
444  
    {
445  
    {
445  
        impl = new implementation(*this);
446  
        impl = new implementation(*this);
446  
    }
447  
    }
447  
    return impl;
448  
    return impl;
448  
}
449  
}
449  

450  

450  
inline void
451  
inline void
451  
timer_service::destroy(io_object::implementation* p)
452  
timer_service::destroy(io_object::implementation* p)
452  
{
453  
{
453  
    destroy_impl(static_cast<implementation&>(*p));
454  
    destroy_impl(static_cast<implementation&>(*p));
454  
}
455  
}
455  

456  

456  
inline void
457  
inline void
457  
timer_service::destroy_impl(implementation& impl)
458  
timer_service::destroy_impl(implementation& impl)
458  
{
459  
{
459  
    // During shutdown the impl is owned by the shutdown loop.
460  
    // During shutdown the impl is owned by the shutdown loop.
460  
    // Re-entering here (from a coroutine-owned timer destructor
461  
    // Re-entering here (from a coroutine-owned timer destructor
461  
    // triggered by h.destroy()) must not modify the heap or
462  
    // triggered by h.destroy()) must not modify the heap or
462  
    // recycle the impl — shutdown deletes it directly.
463  
    // recycle the impl — shutdown deletes it directly.
463  
    if (shutting_down_)
464  
    if (shutting_down_)
464  
        return;
465  
        return;
465  

466  

466  
    cancel_timer(impl);
467  
    cancel_timer(impl);
467  

468  

468  
    if (impl.heap_index_ != (std::numeric_limits<std::size_t>::max)())
469  
    if (impl.heap_index_ != (std::numeric_limits<std::size_t>::max)())
469  
    {
470  
    {
470  
        std::lock_guard lock(mutex_);
471  
        std::lock_guard lock(mutex_);
471  
        remove_timer_impl(impl);
472  
        remove_timer_impl(impl);
472  
        refresh_cached_nearest();
473  
        refresh_cached_nearest();
473  
    }
474  
    }
474  

475  

475  
    if (try_push_tl_cache(&impl))
476  
    if (try_push_tl_cache(&impl))
476  
        return;
477  
        return;
477  

478  

478  
    std::lock_guard lock(mutex_);
479  
    std::lock_guard lock(mutex_);
479  
    impl.next_free_ = free_list_;
480  
    impl.next_free_ = free_list_;
480  
    free_list_      = &impl;
481  
    free_list_      = &impl;
481  
}
482  
}
482  

483  

483  
inline waiter_node*
484  
inline waiter_node*
484  
timer_service::create_waiter()
485  
timer_service::create_waiter()
485  
{
486  
{
486  
    if (auto* w = try_pop_waiter_tl_cache())
487  
    if (auto* w = try_pop_waiter_tl_cache())
487  
        return w;
488  
        return w;
488  

489  

489  
    std::lock_guard lock(mutex_);
490  
    std::lock_guard lock(mutex_);
490  
    if (waiter_free_list_)
491  
    if (waiter_free_list_)
491  
    {
492  
    {
492  
        auto* w           = waiter_free_list_;
493  
        auto* w           = waiter_free_list_;
493  
        waiter_free_list_ = w->next_free_;
494  
        waiter_free_list_ = w->next_free_;
494  
        w->next_free_     = nullptr;
495  
        w->next_free_     = nullptr;
495  
        return w;
496  
        return w;
496  
    }
497  
    }
497  

498  

498  
    return new waiter_node();
499  
    return new waiter_node();
499  
}
500  
}
500  

501  

501  
inline void
502  
inline void
502  
timer_service::destroy_waiter(waiter_node* w)
503  
timer_service::destroy_waiter(waiter_node* w)
503  
{
504  
{
504  
    if (try_push_waiter_tl_cache(w))
505  
    if (try_push_waiter_tl_cache(w))
505  
        return;
506  
        return;
506  

507  

507  
    std::lock_guard lock(mutex_);
508  
    std::lock_guard lock(mutex_);
508  
    w->next_free_     = waiter_free_list_;
509  
    w->next_free_     = waiter_free_list_;
509  
    waiter_free_list_ = w;
510  
    waiter_free_list_ = w;
510  
}
511  
}
511  

512  

512  
inline std::size_t
513  
inline std::size_t
513  
timer_service::update_timer(implementation& impl, time_point new_time)
514  
timer_service::update_timer(implementation& impl, time_point new_time)
514  
{
515  
{
515  
    bool in_heap =
516  
    bool in_heap =
516  
        (impl.heap_index_ != (std::numeric_limits<std::size_t>::max)());
517  
        (impl.heap_index_ != (std::numeric_limits<std::size_t>::max)());
517  
    if (!in_heap && impl.waiters_.empty())
518  
    if (!in_heap && impl.waiters_.empty())
518  
        return 0;
519  
        return 0;
519  

520  

520  
    bool notify = false;
521  
    bool notify = false;
521  
    intrusive_list<waiter_node> canceled;
522  
    intrusive_list<waiter_node> canceled;
522  

523  

523  
    {
524  
    {
524  
        std::lock_guard lock(mutex_);
525  
        std::lock_guard lock(mutex_);
525  

526  

526  
        while (auto* w = impl.waiters_.pop_front())
527  
        while (auto* w = impl.waiters_.pop_front())
527  
        {
528  
        {
528  
            w->impl_ = nullptr;
529  
            w->impl_ = nullptr;
529  
            canceled.push_back(w);
530  
            canceled.push_back(w);
530  
        }
531  
        }
531  

532  

532  
        if (impl.heap_index_ < heap_.size())
533  
        if (impl.heap_index_ < heap_.size())
533  
        {
534  
        {
534  
            time_point old_time           = heap_[impl.heap_index_].time_;
535  
            time_point old_time           = heap_[impl.heap_index_].time_;
535  
            heap_[impl.heap_index_].time_ = new_time;
536  
            heap_[impl.heap_index_].time_ = new_time;
536  

537  

537  
            if (new_time < old_time)
538  
            if (new_time < old_time)
538  
                up_heap(impl.heap_index_);
539  
                up_heap(impl.heap_index_);
539  
            else
540  
            else
540  
                down_heap(impl.heap_index_);
541  
                down_heap(impl.heap_index_);
541  

542  

542  
            notify = (impl.heap_index_ == 0);
543  
            notify = (impl.heap_index_ == 0);
543  
        }
544  
        }
544  

545  

545  
        refresh_cached_nearest();
546  
        refresh_cached_nearest();
546  
    }
547  
    }
547  

548  

548  
    std::size_t count = 0;
549  
    std::size_t count = 0;
549  
    while (auto* w = canceled.pop_front())
550  
    while (auto* w = canceled.pop_front())
550  
    {
551  
    {
551  
        w->ec_value_ = make_error_code(capy::error::canceled);
552  
        w->ec_value_ = make_error_code(capy::error::canceled);
552  
        sched_->post(&w->op_);
553  
        sched_->post(&w->op_);
553  
        ++count;
554  
        ++count;
554  
    }
555  
    }
555  

556  

556  
    if (notify)
557  
    if (notify)
557  
        on_earliest_changed_();
558  
        on_earliest_changed_();
558  

559  

559  
    return count;
560  
    return count;
560  
}
561  
}
561  

562  

562  
inline void
563  
inline void
563  
timer_service::insert_waiter(implementation& impl, waiter_node* w)
564  
timer_service::insert_waiter(implementation& impl, waiter_node* w)
564  
{
565  
{
565  
    bool notify = false;
566  
    bool notify = false;
566  
    {
567  
    {
567  
        std::lock_guard lock(mutex_);
568  
        std::lock_guard lock(mutex_);
568  
        if (impl.heap_index_ == (std::numeric_limits<std::size_t>::max)())
569  
        if (impl.heap_index_ == (std::numeric_limits<std::size_t>::max)())
569  
        {
570  
        {
570  
            impl.heap_index_ = heap_.size();
571  
            impl.heap_index_ = heap_.size();
571  
            heap_.push_back({impl.expiry_, &impl});
572  
            heap_.push_back({impl.expiry_, &impl});
572  
            up_heap(heap_.size() - 1);
573  
            up_heap(heap_.size() - 1);
573  
            notify = (impl.heap_index_ == 0);
574  
            notify = (impl.heap_index_ == 0);
574  
            refresh_cached_nearest();
575  
            refresh_cached_nearest();
575  
        }
576  
        }
576  
        impl.waiters_.push_back(w);
577  
        impl.waiters_.push_back(w);
577  
    }
578  
    }
578  
    if (notify)
579  
    if (notify)
579  
        on_earliest_changed_();
580  
        on_earliest_changed_();
580  
}
581  
}
581  

582  

582  
inline std::size_t
583  
inline std::size_t
583  
timer_service::cancel_timer(implementation& impl)
584  
timer_service::cancel_timer(implementation& impl)
584  
{
585  
{
585  
    if (!impl.might_have_pending_waits_)
586  
    if (!impl.might_have_pending_waits_)
586  
        return 0;
587  
        return 0;
587  

588  

588  
    // Not in heap and no waiters — just clear the flag
589  
    // Not in heap and no waiters — just clear the flag
589  
    if (impl.heap_index_ == (std::numeric_limits<std::size_t>::max)() &&
590  
    if (impl.heap_index_ == (std::numeric_limits<std::size_t>::max)() &&
590  
        impl.waiters_.empty())
591  
        impl.waiters_.empty())
591  
    {
592  
    {
592  
        impl.might_have_pending_waits_ = false;
593  
        impl.might_have_pending_waits_ = false;
593  
        return 0;
594  
        return 0;
594  
    }
595  
    }
595  

596  

596  
    intrusive_list<waiter_node> canceled;
597  
    intrusive_list<waiter_node> canceled;
597  

598  

598  
    {
599  
    {
599  
        std::lock_guard lock(mutex_);
600  
        std::lock_guard lock(mutex_);
600  
        remove_timer_impl(impl);
601  
        remove_timer_impl(impl);
601  
        while (auto* w = impl.waiters_.pop_front())
602  
        while (auto* w = impl.waiters_.pop_front())
602  
        {
603  
        {
603  
            w->impl_ = nullptr;
604  
            w->impl_ = nullptr;
604  
            canceled.push_back(w);
605  
            canceled.push_back(w);
605  
        }
606  
        }
606  
        refresh_cached_nearest();
607  
        refresh_cached_nearest();
607  
    }
608  
    }
608  

609  

609  
    impl.might_have_pending_waits_ = false;
610  
    impl.might_have_pending_waits_ = false;
610  

611  

611  
    std::size_t count = 0;
612  
    std::size_t count = 0;
612  
    while (auto* w = canceled.pop_front())
613  
    while (auto* w = canceled.pop_front())
613  
    {
614  
    {
614  
        w->ec_value_ = make_error_code(capy::error::canceled);
615  
        w->ec_value_ = make_error_code(capy::error::canceled);
615  
        sched_->post(&w->op_);
616  
        sched_->post(&w->op_);
616  
        ++count;
617  
        ++count;
617  
    }
618  
    }
618  

619  

619  
    return count;
620  
    return count;
620  
}
621  
}
621  

622  

622  
inline void
623  
inline void
623  
timer_service::cancel_waiter(waiter_node* w)
624  
timer_service::cancel_waiter(waiter_node* w)
624  
{
625  
{
625  
    {
626  
    {
626  
        std::lock_guard lock(mutex_);
627  
        std::lock_guard lock(mutex_);
627  
        // Already removed by cancel_timer or process_expired
628  
        // Already removed by cancel_timer or process_expired
628  
        if (!w->impl_)
629  
        if (!w->impl_)
629  
            return;
630  
            return;
630  
        auto* impl = w->impl_;
631  
        auto* impl = w->impl_;
631  
        w->impl_   = nullptr;
632  
        w->impl_   = nullptr;
632  
        impl->waiters_.remove(w);
633  
        impl->waiters_.remove(w);
633  
        if (impl->waiters_.empty())
634  
        if (impl->waiters_.empty())
634  
        {
635  
        {
635  
            remove_timer_impl(*impl);
636  
            remove_timer_impl(*impl);
636  
            impl->might_have_pending_waits_ = false;
637  
            impl->might_have_pending_waits_ = false;
637  
        }
638  
        }
638  
        refresh_cached_nearest();
639  
        refresh_cached_nearest();
639  
    }
640  
    }
640  

641  

641  
    w->ec_value_ = make_error_code(capy::error::canceled);
642  
    w->ec_value_ = make_error_code(capy::error::canceled);
642  
    sched_->post(&w->op_);
643  
    sched_->post(&w->op_);
643  
}
644  
}
644  

645  

645  
inline std::size_t
646  
inline std::size_t
646  
timer_service::cancel_one_waiter(implementation& impl)
647  
timer_service::cancel_one_waiter(implementation& impl)
647  
{
648  
{
648  
    if (!impl.might_have_pending_waits_)
649  
    if (!impl.might_have_pending_waits_)
649  
        return 0;
650  
        return 0;
650  

651  

651  
    waiter_node* w = nullptr;
652  
    waiter_node* w = nullptr;
652  

653  

653  
    {
654  
    {
654  
        std::lock_guard lock(mutex_);
655  
        std::lock_guard lock(mutex_);
655  
        w = impl.waiters_.pop_front();
656  
        w = impl.waiters_.pop_front();
656  
        if (!w)
657  
        if (!w)
657  
            return 0;
658  
            return 0;
658  
        w->impl_ = nullptr;
659  
        w->impl_ = nullptr;
659  
        if (impl.waiters_.empty())
660  
        if (impl.waiters_.empty())
660  
        {
661  
        {
661  
            remove_timer_impl(impl);
662  
            remove_timer_impl(impl);
662  
            impl.might_have_pending_waits_ = false;
663  
            impl.might_have_pending_waits_ = false;
663  
        }
664  
        }
664  
        refresh_cached_nearest();
665  
        refresh_cached_nearest();
665  
    }
666  
    }
666  

667  

667  
    w->ec_value_ = make_error_code(capy::error::canceled);
668  
    w->ec_value_ = make_error_code(capy::error::canceled);
668  
    sched_->post(&w->op_);
669  
    sched_->post(&w->op_);
669  
    return 1;
670  
    return 1;
670  
}
671  
}
671  

672  

672  
inline std::size_t
673  
inline std::size_t
673  
timer_service::process_expired()
674  
timer_service::process_expired()
674  
{
675  
{
675  
    intrusive_list<waiter_node> expired;
676  
    intrusive_list<waiter_node> expired;
676  

677  

677  
    {
678  
    {
678  
        std::lock_guard lock(mutex_);
679  
        std::lock_guard lock(mutex_);
679  
        auto now = clock_type::now();
680  
        auto now = clock_type::now();
680  

681  

681  
        while (!heap_.empty() && heap_[0].time_ <= now)
682  
        while (!heap_.empty() && heap_[0].time_ <= now)
682  
        {
683  
        {
683  
            implementation* t = heap_[0].timer_;
684  
            implementation* t = heap_[0].timer_;
684  
            remove_timer_impl(*t);
685  
            remove_timer_impl(*t);
685  
            while (auto* w = t->waiters_.pop_front())
686  
            while (auto* w = t->waiters_.pop_front())
686  
            {
687  
            {
687  
                w->impl_     = nullptr;
688  
                w->impl_     = nullptr;
688  
                w->ec_value_ = {};
689  
                w->ec_value_ = {};
689  
                expired.push_back(w);
690  
                expired.push_back(w);
690  
            }
691  
            }
691  
            t->might_have_pending_waits_ = false;
692  
            t->might_have_pending_waits_ = false;
692  
        }
693  
        }
693  

694  

694  
        refresh_cached_nearest();
695  
        refresh_cached_nearest();
695  
    }
696  
    }
696  

697  

697  
    std::size_t count = 0;
698  
    std::size_t count = 0;
698  
    while (auto* w = expired.pop_front())
699  
    while (auto* w = expired.pop_front())
699  
    {
700  
    {
700  
        sched_->post(&w->op_);
701  
        sched_->post(&w->op_);
701  
        ++count;
702  
        ++count;
702  
    }
703  
    }
703  

704  

704  
    return count;
705  
    return count;
705  
}
706  
}
706  

707  

707  
inline void
708  
inline void
708  
timer_service::remove_timer_impl(implementation& impl)
709  
timer_service::remove_timer_impl(implementation& impl)
709  
{
710  
{
710  
    std::size_t index = impl.heap_index_;
711  
    std::size_t index = impl.heap_index_;
711  
    if (index >= heap_.size())
712  
    if (index >= heap_.size())
712  
        return; // Not in heap
713  
        return; // Not in heap
713  

714  

714  
    if (index == heap_.size() - 1)
715  
    if (index == heap_.size() - 1)
715  
    {
716  
    {
716  
        // Last element, just pop
717  
        // Last element, just pop
717  
        impl.heap_index_ = (std::numeric_limits<std::size_t>::max)();
718  
        impl.heap_index_ = (std::numeric_limits<std::size_t>::max)();
718  
        heap_.pop_back();
719  
        heap_.pop_back();
719  
    }
720  
    }
720  
    else
721  
    else
721  
    {
722  
    {
722  
        // Swap with last and reheapify
723  
        // Swap with last and reheapify
723  
        swap_heap(index, heap_.size() - 1);
724  
        swap_heap(index, heap_.size() - 1);
724  
        impl.heap_index_ = (std::numeric_limits<std::size_t>::max)();
725  
        impl.heap_index_ = (std::numeric_limits<std::size_t>::max)();
725  
        heap_.pop_back();
726  
        heap_.pop_back();
726  

727  

727  
        if (index > 0 && heap_[index].time_ < heap_[(index - 1) / 2].time_)
728  
        if (index > 0 && heap_[index].time_ < heap_[(index - 1) / 2].time_)
728  
            up_heap(index);
729  
            up_heap(index);
729  
        else
730  
        else
730  
            down_heap(index);
731  
            down_heap(index);
731  
    }
732  
    }
732  
}
733  
}
733  

734  

734  
inline void
735  
inline void
735  
timer_service::up_heap(std::size_t index)
736  
timer_service::up_heap(std::size_t index)
736  
{
737  
{
737  
    while (index > 0)
738  
    while (index > 0)
738  
    {
739  
    {
739  
        std::size_t parent = (index - 1) / 2;
740  
        std::size_t parent = (index - 1) / 2;
740  
        if (!(heap_[index].time_ < heap_[parent].time_))
741  
        if (!(heap_[index].time_ < heap_[parent].time_))
741  
            break;
742  
            break;
742  
        swap_heap(index, parent);
743  
        swap_heap(index, parent);
743  
        index = parent;
744  
        index = parent;
744  
    }
745  
    }
745  
}
746  
}
746  

747  

747  
inline void
748  
inline void
748  
timer_service::down_heap(std::size_t index)
749  
timer_service::down_heap(std::size_t index)
749  
{
750  
{
750  
    std::size_t child = index * 2 + 1;
751  
    std::size_t child = index * 2 + 1;
751  
    while (child < heap_.size())
752  
    while (child < heap_.size())
752  
    {
753  
    {
753  
        std::size_t min_child = (child + 1 == heap_.size() ||
754  
        std::size_t min_child = (child + 1 == heap_.size() ||
754  
                                 heap_[child].time_ < heap_[child + 1].time_)
755  
                                 heap_[child].time_ < heap_[child + 1].time_)
755  
            ? child
756  
            ? child
756  
            : child + 1;
757  
            : child + 1;
757  

758  

758  
        if (heap_[index].time_ < heap_[min_child].time_)
759  
        if (heap_[index].time_ < heap_[min_child].time_)
759  
            break;
760  
            break;
760  

761  

761  
        swap_heap(index, min_child);
762  
        swap_heap(index, min_child);
762  
        index = min_child;
763  
        index = min_child;
763  
        child = index * 2 + 1;
764  
        child = index * 2 + 1;
764  
    }
765  
    }
765  
}
766  
}
766  

767  

767  
inline void
768  
inline void
768  
timer_service::swap_heap(std::size_t i1, std::size_t i2)
769  
timer_service::swap_heap(std::size_t i1, std::size_t i2)
769  
{
770  
{
770  
    heap_entry tmp                = heap_[i1];
771  
    heap_entry tmp                = heap_[i1];
771  
    heap_[i1]                     = heap_[i2];
772  
    heap_[i1]                     = heap_[i2];
772  
    heap_[i2]                     = tmp;
773  
    heap_[i2]                     = tmp;
773  
    heap_[i1].timer_->heap_index_ = i1;
774  
    heap_[i1].timer_->heap_index_ = i1;
774  
    heap_[i2].timer_->heap_index_ = i2;
775  
    heap_[i2].timer_->heap_index_ = i2;
775  
}
776  
}
776  

777  

777  
// waiter_node out-of-class member function definitions
778  
// waiter_node out-of-class member function definitions
778  

779  

779  
inline void
780  
inline void
780  
waiter_node::canceller::operator()() const
781  
waiter_node::canceller::operator()() const
781  
{
782  
{
782  
    waiter_->svc_->cancel_waiter(waiter_);
783  
    waiter_->svc_->cancel_waiter(waiter_);
783  
}
784  
}
784  

785  

785  
inline void
786  
inline void
786  
waiter_node::completion_op::do_complete(
787  
waiter_node::completion_op::do_complete(
787  
    [[maybe_unused]] void* owner,
788  
    [[maybe_unused]] void* owner,
788  
    scheduler_op* base,
789  
    scheduler_op* base,
789  
    std::uint32_t,
790  
    std::uint32_t,
790  
    std::uint32_t)
791  
    std::uint32_t)
791  
{
792  
{
792  
    // owner is always non-null here. The destroy path (owner == nullptr)
793  
    // owner is always non-null here. The destroy path (owner == nullptr)
793  
    // is unreachable because completion_op overrides destroy() directly,
794  
    // is unreachable because completion_op overrides destroy() directly,
794  
    // bypassing scheduler_op::destroy() which would call func_(nullptr, ...).
795  
    // bypassing scheduler_op::destroy() which would call func_(nullptr, ...).
795  
    BOOST_COROSIO_ASSERT(owner);
796  
    BOOST_COROSIO_ASSERT(owner);
796  
    static_cast<completion_op*>(base)->operator()();
797  
    static_cast<completion_op*>(base)->operator()();
797  
}
798  
}
798  

799  

799  
inline void
800  
inline void
800  
waiter_node::completion_op::operator()()
801  
waiter_node::completion_op::operator()()
801  
{
802  
{
802  
    auto* w = waiter_;
803  
    auto* w = waiter_;
803  
    w->stop_cb_.reset();
804  
    w->stop_cb_.reset();
804  
    if (w->ec_out_)
805  
    if (w->ec_out_)
805  
        *w->ec_out_ = w->ec_value_;
806  
        *w->ec_out_ = w->ec_value_;
806  

807  

807  
    auto* cont  = w->cont_;
808  
    auto* cont  = w->cont_;
808  
    auto d      = w->d_;
809  
    auto d      = w->d_;
809  
    auto* svc   = w->svc_;
810  
    auto* svc   = w->svc_;
810  
    auto& sched = svc->get_scheduler();
811  
    auto& sched = svc->get_scheduler();
811  

812  

812  
    svc->destroy_waiter(w);
813  
    svc->destroy_waiter(w);
813  

814  

814  
    d.post(*cont);
815  
    d.post(*cont);
815  
    sched.work_finished();
816  
    sched.work_finished();
816  
}
817  
}
817  

818  

818  
// GCC 14 false-positive: inlining ~optional<stop_callback> through
819  
// GCC 14 false-positive: inlining ~optional<stop_callback> through
819  
// delete loses track that stop_cb_ was already .reset() above.
820  
// delete loses track that stop_cb_ was already .reset() above.
820  
#if defined(__GNUC__) && !defined(__clang__)
821  
#if defined(__GNUC__) && !defined(__clang__)
821  
#pragma GCC diagnostic push
822  
#pragma GCC diagnostic push
822  
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
823  
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
823  
#endif
824  
#endif
824  
inline void
825  
inline void
825  
waiter_node::completion_op::destroy()
826  
waiter_node::completion_op::destroy()
826  
{
827  
{
827  
    // Called during scheduler shutdown drain when this completion_op is
828  
    // Called during scheduler shutdown drain when this completion_op is
828  
    // in the scheduler's ready queue (posted by cancel_timer() or
829  
    // in the scheduler's ready queue (posted by cancel_timer() or
829  
    // process_expired()). Balances the work_started() from
830  
    // process_expired()). Balances the work_started() from
830  
    // implementation::wait(). The scheduler drain loop separately
831  
    // implementation::wait(). The scheduler drain loop separately
831  
    // balances the work_started() from post(). On IOCP both decrements
832  
    // balances the work_started() from post(). On IOCP both decrements
832  
    // are required for outstanding_work_ to reach zero; on other
833  
    // are required for outstanding_work_ to reach zero; on other
833  
    // backends this is harmless.
834  
    // backends this is harmless.
834  
    //
835  
    //
835  
    // This override also prevents scheduler_op::destroy() from calling
836  
    // This override also prevents scheduler_op::destroy() from calling
836  
    // do_complete(nullptr, ...). See also: timer_service::shutdown()
837  
    // do_complete(nullptr, ...). See also: timer_service::shutdown()
837  
    // which drains waiters still in the timer heap (the other path).
838  
    // which drains waiters still in the timer heap (the other path).
838  
    auto* w = waiter_;
839  
    auto* w = waiter_;
839  
    w->stop_cb_.reset();
840  
    w->stop_cb_.reset();
840  
    auto h      = std::exchange(w->h_, {});
841  
    auto h      = std::exchange(w->h_, {});
841  
    auto& sched = w->svc_->get_scheduler();
842  
    auto& sched = w->svc_->get_scheduler();
842  
    delete w;
843  
    delete w;
843  
    sched.work_finished();
844  
    sched.work_finished();
844  
    if (h)
845  
    if (h)
845  
        h.destroy();
846  
        h.destroy();
846  
}
847  
}
847  
#if defined(__GNUC__) && !defined(__clang__)
848  
#if defined(__GNUC__) && !defined(__clang__)
848  
#pragma GCC diagnostic pop
849  
#pragma GCC diagnostic pop
849  
#endif
850  
#endif
850  

851  

851  
inline std::coroutine_handle<>
852  
inline std::coroutine_handle<>
852  
timer_service::implementation::wait(
853  
timer_service::implementation::wait(
853  
    std::coroutine_handle<> h,
854  
    std::coroutine_handle<> h,
854  
    capy::executor_ref d,
855  
    capy::executor_ref d,
855  
    std::stop_token token,
856  
    std::stop_token token,
856  
    std::error_code* ec,
857  
    std::error_code* ec,
857  
    capy::continuation* cont)
858  
    capy::continuation* cont)
858  
{
859  
{
859  
    // Already-expired fast path — no waiter_node, no mutex.
860  
    // Already-expired fast path — no waiter_node, no mutex.
860  
    // Post instead of dispatch so the coroutine yields to the
861  
    // Post instead of dispatch so the coroutine yields to the
861  
    // scheduler, allowing other queued work to run.
862  
    // scheduler, allowing other queued work to run.
862  
    if (heap_index_ == (std::numeric_limits<std::size_t>::max)())
863  
    if (heap_index_ == (std::numeric_limits<std::size_t>::max)())
863  
    {
864  
    {
864  
        if (expiry_ == (time_point::min)() || expiry_ <= clock_type::now())
865  
        if (expiry_ == (time_point::min)() || expiry_ <= clock_type::now())
865  
        {
866  
        {
866  
            if (ec)
867  
            if (ec)
867  
                *ec = {};
868  
                *ec = {};
868  
            d.post(*cont);
869  
            d.post(*cont);
869  
            return std::noop_coroutine();
870  
            return std::noop_coroutine();
870  
        }
871  
        }
871  
    }
872  
    }
872  

873  

873  
    auto* w    = svc_->create_waiter();
874  
    auto* w    = svc_->create_waiter();
874  
    w->impl_   = this;
875  
    w->impl_   = this;
875  
    w->svc_    = svc_;
876  
    w->svc_    = svc_;
876  
    w->h_      = h;
877  
    w->h_      = h;
877  
    w->cont_   = cont;
878  
    w->cont_   = cont;
878  
    w->d_      = d;
879  
    w->d_      = d;
879  
    w->token_  = std::move(token);
880  
    w->token_  = std::move(token);
880  
    w->ec_out_ = ec;
881  
    w->ec_out_ = ec;
881  

882  

882  
    svc_->insert_waiter(*this, w);
883  
    svc_->insert_waiter(*this, w);
883  
    might_have_pending_waits_ = true;
884  
    might_have_pending_waits_ = true;
884  
    svc_->get_scheduler().work_started();
885  
    svc_->get_scheduler().work_started();
885  

886  

886  
    if (w->token_.stop_possible())
887  
    if (w->token_.stop_possible())
887  
        w->stop_cb_.emplace(w->token_, waiter_node::canceller{w});
888  
        w->stop_cb_.emplace(w->token_, waiter_node::canceller{w});
888  

889  

889  
    return std::noop_coroutine();
890  
    return std::noop_coroutine();
890  
}
891  
}
891  

892  

892  
// Free functions
893  
// Free functions
893  

894  

894  
struct timer_service_access
895  
struct timer_service_access
895  
{
896  
{
896 -
    static timer_service& get_timer(io_context& ctx) noexcept
897 +
    static native_scheduler& get_scheduler(io_context& ctx) noexcept
897 -
    {
 
898 -
        return *ctx.timer_svc_;
 
899 -
    }
 
900 -

 
901 -
    static void set_timer(io_context& ctx, timer_service& svc) noexcept
 
902  
    {
898  
    {
903 -
        ctx.timer_svc_ = &svc;
899 +
        return static_cast<native_scheduler&>(*ctx.sched_);
904  
    }
900  
    }
905  
};
901  
};
906  

902  

907 -
// Bypass find_service() mutex by reading io_context's cached pointer
903 +
// Bypass find_service() mutex by reading the scheduler's cached pointer
908  
inline io_object::io_service&
904  
inline io_object::io_service&
909  
timer_service_direct(capy::execution_context& ctx) noexcept
905  
timer_service_direct(capy::execution_context& ctx) noexcept
910  
{
906  
{
911 -
    return timer_service_access::get_timer(static_cast<io_context&>(ctx));
907 +
    return *timer_service_access::get_scheduler(static_cast<io_context&>(ctx))
 
908 +
                .timer_svc_;
912  
}
909  
}
913  

910  

914  
inline std::size_t
911  
inline std::size_t
915  
timer_service_update_expiry(timer::implementation& base)
912  
timer_service_update_expiry(timer::implementation& base)
916  
{
913  
{
917  
    auto& impl = static_cast<timer_service::implementation&>(base);
914  
    auto& impl = static_cast<timer_service::implementation&>(base);
918  
    return impl.svc_->update_timer(impl, impl.expiry_);
915  
    return impl.svc_->update_timer(impl, impl.expiry_);
919  
}
916  
}
920  

917  

921  
inline std::size_t
918  
inline std::size_t
922  
timer_service_cancel(timer::implementation& base) noexcept
919  
timer_service_cancel(timer::implementation& base) noexcept
923  
{
920  
{
924  
    auto& impl = static_cast<timer_service::implementation&>(base);
921  
    auto& impl = static_cast<timer_service::implementation&>(base);
925  
    return impl.svc_->cancel_timer(impl);
922  
    return impl.svc_->cancel_timer(impl);
926  
}
923  
}
927  

924  

928  
inline std::size_t
925  
inline std::size_t
929  
timer_service_cancel_one(timer::implementation& base) noexcept
926  
timer_service_cancel_one(timer::implementation& base) noexcept
930  
{
927  
{
931  
    auto& impl = static_cast<timer_service::implementation&>(base);
928  
    auto& impl = static_cast<timer_service::implementation&>(base);
932  
    return impl.svc_->cancel_one_waiter(impl);
929  
    return impl.svc_->cancel_one_waiter(impl);
933  
}
930  
}
934  

931  

935  
inline timer_service&
932  
inline timer_service&
936  
get_timer_service(capy::execution_context& ctx, scheduler& sched)
933  
get_timer_service(capy::execution_context& ctx, scheduler& sched)
937  
{
934  
{
938 -
    auto& svc = ctx.make_service<timer_service>(sched);
935 +
    return ctx.make_service<timer_service>(sched);
939 -
    timer_service_access::set_timer(static_cast<io_context&>(ctx), svc);
 
940 -
    return svc;
 
941  
}
936  
}
942  

937  

943  
} // namespace boost::corosio::detail
938  
} // namespace boost::corosio::detail
944  

939  

945  
#endif
940  
#endif