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

23  

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

34  

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

36  

38  
struct scheduler;
37  
struct scheduler;
39  

38  

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

42  

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

48  

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

52  

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

57  

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

67  

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

73  

75  
struct BOOST_COROSIO_SYMBOL_VISIBLE waiter_node;
74  
struct BOOST_COROSIO_SYMBOL_VISIBLE waiter_node;
76  

75  

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

77  

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

87  

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

93  

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

97  

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

100  

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

106  

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

114  

116  
    struct implementation;
115  
    struct implementation;
117  

116  

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

123  

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

134  

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

141  

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

147  

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

150  

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

153  

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

159  

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

166  

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

173  

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

176  

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

179  

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

182  

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

185  

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

188  

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

191  

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

194  

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

197  

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

200  

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

203  

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

206  

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

209  

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

217  

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

223  

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

231  

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

234  

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

236  

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

240  

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

247  

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

260  

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

266  

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

272  

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

275  

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

278  

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

280  

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

288  

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

293  

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

296  

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

311  

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

322  

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

334  

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

345  

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

351  

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

355  

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

357  

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

363  

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

369  

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

384  

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

403  

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

411  

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

420  

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

432  

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

449  

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

455  

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

465  

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

467  

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

474  

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

477  

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

482  

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

488  

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

497  

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

500  

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

506  

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

511  

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

519  

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

522  

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

525  

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

531  

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

536  

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

541  

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

544  

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

547  

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

555  

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

558  

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

561  

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

581  

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

587  

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

595  

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

597  

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

608  

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

610  

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

618  

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

621  

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

640  

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

644  

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

650  

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

652  

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

666  

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

671  

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

676  

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

680  

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

693  

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

696  

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

703  

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

706  

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

713  

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

726  

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

733  

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

746  

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

757  

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

760  

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

766  

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

776  

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

778  

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

784  

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

798  

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

806  

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

811  

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

813  

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

817  

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

850  

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

872  

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

881  

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

885  

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

888  

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

891  

893  
// Free functions
892  
// Free functions
894  

893  

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

 
901 +
    static void set_timer(io_context& ctx, timer_service& svc) noexcept
 
902 +
    {
 
903 +
        ctx.timer_svc_ = &svc;
900  
    }
904  
    }
901  
};
905  
};
902  

906  

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

913  

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

920  

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

927  

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

934  

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

942  

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

944  

940  
#endif
945  
#endif