Corium 1.1.0
High-Performance Zero-Heap C++20 MPSC Application Runtime
Loading...
Searching...
No Matches
CancellationToken.hpp
Go to the documentation of this file.
1
7#pragma once
8
9#include <atomic>
10#include <coroutine>
11
12namespace corium::async {
13
17public:
18 constexpr CancellationToken() noexcept = default;
19
22 void cancel() noexcept
23 {
24 _cancelled.store(true, std::memory_order_release);
25 auto handle = _waiter.exchange(nullptr, std::memory_order_acq_rel);
26 if (handle && !handle.done()) {
27 handle.resume();
28 }
29 }
30
33 [[nodiscard]] bool isCancelled() const noexcept
34 {
35 return _cancelled.load(std::memory_order_acquire);
36 }
37
40 void reset() noexcept
41 {
42 _cancelled.store(false, std::memory_order_release);
43 _waiter.store(nullptr, std::memory_order_release);
44 }
45
49
50 [[nodiscard]] bool await_ready() const noexcept
51 {
52 return token.isCancelled();
53 }
54
55 bool await_suspend(std::coroutine_handle<> h) noexcept
56 {
57 if (token.isCancelled()) {
58 return false; // do not suspend
59 }
60 token._waiter.store(h, std::memory_order_release);
61 return !token.isCancelled();
62 }
63
64 constexpr void await_resume() const noexcept {}
65 };
66
74 [[nodiscard]] WhenCancelledAwaiter whenCancelled() noexcept
75 {
76 return WhenCancelledAwaiter{*this};
77 }
78
79private:
80 std::atomic<bool> _cancelled{false};
81 std::atomic<std::coroutine_handle<>> _waiter{nullptr};
82};
83
84} // namespace corium::async
Lightweight, zero-heap cooperative cancellation token for C++20 coroutines and services.
Definition CancellationToken.hpp:16
void reset() noexcept
Reset token state to uncancelled.
Definition CancellationToken.hpp:40
constexpr CancellationToken() noexcept=default
void cancel() noexcept
Signal cancellation to all observing tasks.
Definition CancellationToken.hpp:22
bool isCancelled() const noexcept
Check if cancellation has been requested.
Definition CancellationToken.hpp:33
WhenCancelledAwaiter whenCancelled() noexcept
Definition CancellationToken.hpp:74
Definition AsyncEvent.hpp:14
Awaitable that suspends until this token is cancelled.
Definition CancellationToken.hpp:47
bool await_ready() const noexcept
Definition CancellationToken.hpp:50
constexpr void await_resume() const noexcept
Definition CancellationToken.hpp:64
CancellationToken & token
Definition CancellationToken.hpp:48
bool await_suspend(std::coroutine_handle<> h) noexcept
Definition CancellationToken.hpp:55