Thread System 0.3.1
High-performance C++20 thread pool with work stealing and DAG scheduling
Loading...
Searching...
No Matches
kcenon::thread::enhanced_cancellation_token Class Reference

Advanced cancellation token with timeout, deadline, and reason support. More...

#include <enhanced_cancellation_token.h>

Collaboration diagram for kcenon::thread::enhanced_cancellation_token:
Collaboration graph

Classes

struct  state
 

Public Types

using callback_handle = std::size_t
 Callback handle type for registration management.
 
using callback_type = std::function<void()>
 Simple callback function type.
 
using callback_with_reason_type
 Callback function type with reason parameter.
 

Public Member Functions

 enhanced_cancellation_token ()
 Default constructor creates a new token.
 
 enhanced_cancellation_token (const enhanced_cancellation_token &)=default
 Copy constructor (shares state).
 
 enhanced_cancellation_token (enhanced_cancellation_token &&) noexcept=default
 Move constructor.
 
auto operator= (const enhanced_cancellation_token &) -> enhanced_cancellation_token &=default
 Copy assignment (shares state).
 
auto operator= (enhanced_cancellation_token &&) noexcept -> enhanced_cancellation_token &=default
 Move assignment.
 
 ~enhanced_cancellation_token ()
 Destructor.
 
auto cancel () -> void
 Cancels the token.
 
auto cancel (const std::string &message) -> void
 Cancels the token with a message.
 
auto cancel (std::exception_ptr ex) -> void
 Cancels the token with an exception.
 
auto is_cancelled () const -> bool
 Checks if the token has been cancelled.
 
auto is_cancellation_requested () const -> bool
 Checks if cancellation has been requested.
 
auto get_reason () const -> std::optional< cancellation_reason >
 Gets the cancellation reason.
 
auto check_cancelled () const -> common::VoidResult
 Checks if the token has been cancelled and returns an error result.
 
auto has_timeout () const -> bool
 Checks if the token has a timeout or deadline.
 
auto remaining_time () const -> std::chrono::milliseconds
 Gets the remaining time before timeout/deadline.
 
auto deadline () const -> std::chrono::steady_clock::time_point
 Gets the deadline time point.
 
auto extend_timeout (std::chrono::milliseconds additional) -> void
 Extends the timeout by the specified duration.
 
auto register_callback (callback_type callback) -> callback_handle
 Registers a callback to be invoked on cancellation.
 
auto register_callback (callback_with_reason_type callback) -> callback_handle
 Registers a callback that receives the cancellation reason.
 
auto unregister_callback (callback_handle handle) -> void
 Unregisters a previously registered callback.
 
auto wait () const -> void
 Waits until the token is cancelled.
 
auto wait_for (std::chrono::milliseconds timeout) const -> bool
 Waits for cancellation with a timeout.
 
auto wait_until (std::chrono::steady_clock::time_point deadline) const -> bool
 Waits for cancellation until a deadline.
 

Static Public Member Functions

static auto create () -> enhanced_cancellation_token
 Creates a new cancellation token.
 
static auto create_with_timeout (std::chrono::milliseconds timeout) -> enhanced_cancellation_token
 Creates a token that auto-cancels after the specified timeout.
 
static auto create_with_deadline (std::chrono::steady_clock::time_point deadline) -> enhanced_cancellation_token
 Creates a token that auto-cancels at the specified deadline.
 
static auto create_linked (std::initializer_list< enhanced_cancellation_token > tokens) -> enhanced_cancellation_token
 Creates a token linked to parent tokens.
 
static auto create_linked_with_timeout (const enhanced_cancellation_token &parent, std::chrono::milliseconds timeout) -> enhanced_cancellation_token
 Creates a linked token with additional timeout.
 

Private Member Functions

 enhanced_cancellation_token (std::shared_ptr< state > state)
 
auto do_cancel (cancellation_reason::type reason_type, const std::string &message, std::optional< std::exception_ptr > ex) -> void
 

Static Private Member Functions

static auto start_timeout_timer (std::weak_ptr< state > state_weak, std::chrono::steady_clock::time_point deadline) -> void
 

Private Attributes

std::shared_ptr< statestate_
 

Detailed Description

Advanced cancellation token with timeout, deadline, and reason support.

Extends the basic cancellation_token with additional features:

  • Timeout-based automatic cancellation
  • Deadline-based automatic cancellation
  • Cancellation reason tracking
  • Hierarchical token linking
  • Callback registration with handles
  • Wait methods with timeout support

Design Principles

  • Thread Safe: All operations are safe for concurrent access
  • Efficient: Minimal overhead when not cancelled
  • Composable: Tokens can be linked to create hierarchies
  • Observable: Callbacks notify when cancellation occurs

Usage Example

// Create token with 30 second timeout
std::chrono::seconds{30});
// Use in a worker loop
while (!token.is_cancelled()) {
do_work_chunk();
}
// Check reason if cancelled
if (auto reason = token.get_reason()) {
std::cout << "Cancelled: " << reason->to_string() << std::endl;
}
static auto create_with_timeout(std::chrono::milliseconds timeout) -> enhanced_cancellation_token
Creates a token that auto-cancels after the specified timeout.
See also
cancellation_token For basic Cancellation functionality
cancellation_reason For Cancellation reason details

Definition at line 75 of file enhanced_cancellation_token.h.

Member Typedef Documentation

◆ callback_handle

Callback handle type for registration management.

Definition at line 83 of file enhanced_cancellation_token.h.

◆ callback_type

Simple callback function type.

Definition at line 86 of file enhanced_cancellation_token.h.

◆ callback_with_reason_type

Initial value:
std::function<void(const cancellation_reason&)>

Callback function type with reason parameter.

Definition at line 89 of file enhanced_cancellation_token.h.

Constructor & Destructor Documentation

◆ enhanced_cancellation_token() [1/4]

kcenon::thread::enhanced_cancellation_token::enhanced_cancellation_token ( )

Default constructor creates a new token.

Definition at line 40 of file enhanced_cancellation_token.cpp.

41 : state_(std::make_shared<state>())
42 {
43 }

◆ enhanced_cancellation_token() [2/4]

kcenon::thread::enhanced_cancellation_token::enhanced_cancellation_token ( const enhanced_cancellation_token & )
default

Copy constructor (shares state).

◆ enhanced_cancellation_token() [3/4]

kcenon::thread::enhanced_cancellation_token::enhanced_cancellation_token ( enhanced_cancellation_token && )
defaultnoexcept

Move constructor.

◆ ~enhanced_cancellation_token()

kcenon::thread::enhanced_cancellation_token::~enhanced_cancellation_token ( )

Destructor.

Definition at line 51 of file enhanced_cancellation_token.cpp.

52 {
53 // If this is the last reference and timer is active, signal it to stop
54 if (state_ && state_.use_count() == 1)
55 {
56 state_->timer_should_stop.store(true, std::memory_order_release);
57 state_->cv.notify_all();
58 }
59 }

References state_.

◆ enhanced_cancellation_token() [4/4]

kcenon::thread::enhanced_cancellation_token::enhanced_cancellation_token ( std::shared_ptr< state > state)
explicitprivate

Definition at line 45 of file enhanced_cancellation_token.cpp.

47 : state_(std::move(state))
48 {
49 }

Member Function Documentation

◆ cancel() [1/3]

auto kcenon::thread::enhanced_cancellation_token::cancel ( ) -> void

Cancels the token.

Sets the token to cancelled state with reason_type::user_requested and invokes all registered callbacks.

Definition at line 219 of file enhanced_cancellation_token.cpp.

220 {
222 }
auto do_cancel(cancellation_reason::type reason_type, const std::string &message, std::optional< std::exception_ptr > ex) -> void
@ user_requested
Explicit cancel() call by user.

References kcenon::thread::cancellation_reason::user_requested.

◆ cancel() [2/3]

auto kcenon::thread::enhanced_cancellation_token::cancel ( const std::string & message) -> void

Cancels the token with a message.

Parameters
messageHuman-readable reason for cancellation.

Definition at line 224 of file enhanced_cancellation_token.cpp.

225 {
227 }

References kcenon::thread::cancellation_reason::user_requested.

◆ cancel() [3/3]

auto kcenon::thread::enhanced_cancellation_token::cancel ( std::exception_ptr ex) -> void

Cancels the token with an exception.

Parameters
exException that caused the cancellation.

The cancellation reason_type will be set to error.

Definition at line 229 of file enhanced_cancellation_token.cpp.

230 {
232 }
@ error
Cancellation triggered by an error.

References kcenon::thread::cancellation_reason::error.

◆ check_cancelled()

auto kcenon::thread::enhanced_cancellation_token::check_cancelled ( ) const -> common::VoidResult
nodiscard

Checks if the token has been cancelled and returns an error result.

Returns
common::VoidResult — error with operation_canceled if cancelled, success otherwise

Definition at line 300 of file enhanced_cancellation_token.cpp.

301 {
302 if (is_cancelled())
303 {
304 auto reason = get_reason();
305 std::string msg = "Operation cancelled";
306 if (reason && !reason->message.empty())
307 {
308 msg += ": " + reason->message;
309 }
311 }
312 return common::ok();
313 }
auto is_cancelled() const -> bool
Checks if the token has been cancelled.
auto get_reason() const -> std::optional< cancellation_reason >
Gets the cancellation reason.
common::VoidResult make_error_result(error_code code, const std::string &message="")
Create a common::VoidResult error from a thread::error_code.

References get_reason(), is_cancelled(), kcenon::thread::make_error_result(), and kcenon::thread::operation_canceled.

Referenced by kcenon::thread::cancellation_scope::check_cancelled().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ create()

auto kcenon::thread::enhanced_cancellation_token::create ( ) -> enhanced_cancellation_token
staticnodiscard

Creates a new cancellation token.

Returns
A new enhanced_cancellation_token.

Definition at line 61 of file enhanced_cancellation_token.cpp.

62 {
64 }
enhanced_cancellation_token()
Default constructor creates a new token.

Referenced by kcenon::thread::cancellation_context::current().

Here is the caller graph for this function:

◆ create_linked()

auto kcenon::thread::enhanced_cancellation_token::create_linked ( std::initializer_list< enhanced_cancellation_token > tokens) -> enhanced_cancellation_token
staticnodiscard

Creates a token linked to parent tokens.

Parameters
tokensParent tokens to link with.
Returns
A new linked token.

The new token will be cancelled when any of the parent tokens are cancelled, with reason_type::parent_cancelled.

Definition at line 88 of file enhanced_cancellation_token.cpp.

91 {
92 auto new_token = create();
93 std::weak_ptr<state> new_state_weak = new_token.state_;
94
95 for (const auto& parent : tokens)
96 {
97 auto parent_copy = parent;
98 parent_copy.register_callback(
99 [new_state_weak](const cancellation_reason& /*parent_reason*/)
100 {
101 if (auto s = new_state_weak.lock())
102 {
103 std::vector<callback_type> simple_to_invoke;
104 std::vector<callback_with_reason_type> reason_to_invoke;
105 cancellation_reason new_reason;
106
107 {
108 std::lock_guard<std::mutex> lock(s->mutex);
109 bool was_cancelled =
110 s->is_cancelled.exchange(true, std::memory_order_release);
111 if (!was_cancelled)
112 {
113 new_reason.reason_type =
115 new_reason.message = "Parent token was cancelled";
116 new_reason.cancel_time = std::chrono::steady_clock::now();
117 s->reason = new_reason;
118
119 for (auto& [handle, cb] : s->simple_callbacks)
120 {
121 simple_to_invoke.push_back(std::move(cb));
122 }
123 s->simple_callbacks.clear();
124
125 for (auto& [handle, cb] : s->reason_callbacks)
126 {
127 reason_to_invoke.push_back(std::move(cb));
128 }
129 s->reason_callbacks.clear();
130 }
131 }
132
133 s->cv.notify_all();
134
135 for (const auto& cb : simple_to_invoke)
136 {
137 cb();
138 }
139 for (const auto& cb : reason_to_invoke)
140 {
141 cb(new_reason);
142 }
143 }
144 });
145 }
146
147 return new_token;
148 }
static auto create() -> enhanced_cancellation_token
Creates a new cancellation token.
@ parent_cancelled
Parent token was cancelled.

References kcenon::thread::cancellation_reason::cancel_time, kcenon::thread::cancellation_reason::message, kcenon::thread::cancellation_reason::parent_cancelled, and kcenon::thread::cancellation_reason::reason_type.

◆ create_linked_with_timeout()

auto kcenon::thread::enhanced_cancellation_token::create_linked_with_timeout ( const enhanced_cancellation_token & parent,
std::chrono::milliseconds timeout ) -> enhanced_cancellation_token
staticnodiscard

Creates a linked token with additional timeout.

Parameters
parentParent token to link with.
timeoutAdditional timeout duration.
Returns
A new linked token with timeout.

The token cancels when either:

  • The parent token is cancelled (reason: parent_cancelled)
  • The timeout expires (reason: timeout)

Definition at line 150 of file enhanced_cancellation_token.cpp.

153 {
154 auto deadline_point = std::chrono::steady_clock::now() + timeout;
155
156 auto token = create();
157 token.state_->deadline_point = deadline_point;
158 token.state_->has_deadline.store(true, std::memory_order_release);
159
160 // Link to parent
161 std::weak_ptr<state> token_state_weak = token.state_;
162 auto parent_copy = parent;
163 parent_copy.register_callback(
164 [token_state_weak](const cancellation_reason& /*parent_reason*/)
165 {
166 if (auto s = token_state_weak.lock())
167 {
168 std::vector<callback_type> simple_to_invoke;
169 std::vector<callback_with_reason_type> reason_to_invoke;
170 cancellation_reason new_reason;
171
172 {
173 std::lock_guard<std::mutex> lock(s->mutex);
174 bool was_cancelled =
175 s->is_cancelled.exchange(true, std::memory_order_release);
176 if (!was_cancelled)
177 {
178 new_reason.reason_type =
180 new_reason.message = "Parent token was cancelled";
181 new_reason.cancel_time = std::chrono::steady_clock::now();
182 s->reason = new_reason;
183
184 for (auto& [handle, cb] : s->simple_callbacks)
185 {
186 simple_to_invoke.push_back(std::move(cb));
187 }
188 s->simple_callbacks.clear();
189
190 for (auto& [handle, cb] : s->reason_callbacks)
191 {
192 reason_to_invoke.push_back(std::move(cb));
193 }
194 s->reason_callbacks.clear();
195
196 s->timer_should_stop.store(true, std::memory_order_release);
197 }
198 }
199
200 s->cv.notify_all();
201
202 for (const auto& cb : simple_to_invoke)
203 {
204 cb();
205 }
206 for (const auto& cb : reason_to_invoke)
207 {
208 cb(new_reason);
209 }
210 }
211 });
212
213 // Start timeout timer
214 start_timeout_timer(token_state_weak, deadline_point);
215
216 return token;
217 }
static auto start_timeout_timer(std::weak_ptr< state > state_weak, std::chrono::steady_clock::time_point deadline) -> void

References kcenon::thread::cancellation_reason::cancel_time, kcenon::thread::cancellation_reason::message, kcenon::thread::cancellation_reason::parent_cancelled, and kcenon::thread::cancellation_reason::reason_type.

◆ create_with_deadline()

auto kcenon::thread::enhanced_cancellation_token::create_with_deadline ( std::chrono::steady_clock::time_point deadline) -> enhanced_cancellation_token
staticnodiscard

Creates a token that auto-cancels at the specified deadline.

Parameters
deadlineTime point at which the token auto-cancels.
Returns
A new token with deadline.

The token will automatically cancel with reason_type::deadline when the specified time point is reached.

Definition at line 73 of file enhanced_cancellation_token.cpp.

76 {
77 auto token = create();
78 token.state_->deadline_point = deadline_point;
79 token.state_->has_deadline.store(true, std::memory_order_release);
80
81 // Start timeout timer in background
82 std::weak_ptr<state> state_weak = token.state_;
83 start_timeout_timer(state_weak, deadline_point);
84
85 return token;
86 }

◆ create_with_timeout()

auto kcenon::thread::enhanced_cancellation_token::create_with_timeout ( std::chrono::milliseconds timeout) -> enhanced_cancellation_token
staticnodiscard

Creates a token that auto-cancels after the specified timeout.

Parameters
timeoutDuration after which the token auto-cancels.
Returns
A new token with timeout.

The token will automatically cancel with reason_type::timeout when the specified duration elapses from the creation time.

Definition at line 66 of file enhanced_cancellation_token.cpp.

68 {
69 auto deadline_point = std::chrono::steady_clock::now() + timeout;
70 return create_with_deadline(deadline_point);
71 }
static auto create_with_deadline(std::chrono::steady_clock::time_point deadline) -> enhanced_cancellation_token
Creates a token that auto-cancels at the specified deadline.

◆ deadline()

auto kcenon::thread::enhanced_cancellation_token::deadline ( ) const -> std::chrono::steady_clock::time_point
nodiscard

Gets the deadline time point.

Returns
The deadline if set, or time_point::max() if none.

Definition at line 340 of file enhanced_cancellation_token.cpp.

342 {
343 return state_->deadline_point;
344 }

References state_.

◆ do_cancel()

auto kcenon::thread::enhanced_cancellation_token::do_cancel ( cancellation_reason::type reason_type,
const std::string & message,
std::optional< std::exception_ptr > ex ) -> void
private

Definition at line 234 of file enhanced_cancellation_token.cpp.

238 {
239 std::vector<callback_type> simple_to_invoke;
240 std::vector<callback_with_reason_type> reason_to_invoke;
241 cancellation_reason new_reason;
242
243 {
244 std::lock_guard<std::mutex> lock(state_->mutex);
245 bool was_cancelled =
246 state_->is_cancelled.exchange(true, std::memory_order_release);
247 if (!was_cancelled)
248 {
249 new_reason.reason_type = reason_type;
250 new_reason.message = message;
251 new_reason.cancel_time = std::chrono::steady_clock::now();
252 new_reason.exception = ex;
253 state_->reason = new_reason;
254
255 for (auto& [handle, cb] : state_->simple_callbacks)
256 {
257 simple_to_invoke.push_back(std::move(cb));
258 }
259 state_->simple_callbacks.clear();
260
261 for (auto& [handle, cb] : state_->reason_callbacks)
262 {
263 reason_to_invoke.push_back(std::move(cb));
264 }
265 state_->reason_callbacks.clear();
266
267 state_->timer_should_stop.store(true, std::memory_order_release);
268 }
269 }
270
271 state_->cv.notify_all();
272
273 for (const auto& cb : simple_to_invoke)
274 {
275 cb();
276 }
277 for (const auto& cb : reason_to_invoke)
278 {
279 cb(new_reason);
280 }
281 }

References kcenon::thread::cancellation_reason::cancel_time, kcenon::thread::cancellation_reason::exception, kcenon::thread::cancellation_reason::message, and kcenon::thread::cancellation_reason::reason_type.

◆ extend_timeout()

auto kcenon::thread::enhanced_cancellation_token::extend_timeout ( std::chrono::milliseconds additional) -> void

Extends the timeout by the specified duration.

Parameters
additionalAdditional time to add to the deadline.

Definition at line 346 of file enhanced_cancellation_token.cpp.

348 {
349 std::lock_guard<std::mutex> lock(state_->mutex);
350 if (state_->has_deadline.load(std::memory_order_acquire))
351 {
352 state_->deadline_point += additional;
353 }
354 }

◆ get_reason()

auto kcenon::thread::enhanced_cancellation_token::get_reason ( ) const -> std::optional<cancellation_reason>
nodiscard

Gets the cancellation reason.

Returns
The cancellation reason if cancelled, std::nullopt otherwise.

Definition at line 293 of file enhanced_cancellation_token.cpp.

295 {
296 std::lock_guard<std::mutex> lock(state_->mutex);
297 return state_->reason;
298 }

References state_.

Referenced by check_cancelled().

Here is the caller graph for this function:

◆ has_timeout()

auto kcenon::thread::enhanced_cancellation_token::has_timeout ( ) const -> bool
nodiscard

Checks if the token has a timeout or deadline.

Returns
true if the token has a timeout/deadline, false otherwise.

Definition at line 315 of file enhanced_cancellation_token.cpp.

316 {
317 return state_->has_deadline.load(std::memory_order_acquire);
318 }

References state_.

Referenced by remaining_time().

Here is the caller graph for this function:

◆ is_cancellation_requested()

auto kcenon::thread::enhanced_cancellation_token::is_cancellation_requested ( ) const -> bool
nodiscard

Checks if cancellation has been requested.

Returns
true if cancellation is requested, false otherwise.

This is functionally equivalent to is_cancelled() for this implementation.

Definition at line 288 of file enhanced_cancellation_token.cpp.

289 {
290 return is_cancelled();
291 }

References is_cancelled().

Here is the call graph for this function:

◆ is_cancelled()

auto kcenon::thread::enhanced_cancellation_token::is_cancelled ( ) const -> bool
nodiscard

Checks if the token has been cancelled.

Returns
true if cancelled, false otherwise.

Definition at line 283 of file enhanced_cancellation_token.cpp.

284 {
285 return state_->is_cancelled.load(std::memory_order_acquire);
286 }

References is_cancelled(), and state_.

Referenced by check_cancelled(), is_cancellation_requested(), kcenon::thread::cancellation_scope::is_cancelled(), and is_cancelled().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ operator=() [1/2]

auto kcenon::thread::enhanced_cancellation_token::operator= ( const enhanced_cancellation_token & ) -> enhanced_cancellation_token &=default
default

Copy assignment (shares state).

◆ operator=() [2/2]

auto kcenon::thread::enhanced_cancellation_token::operator= ( enhanced_cancellation_token && ) -> enhanced_cancellation_token &=default
defaultnoexcept

Move assignment.

◆ register_callback() [1/2]

auto kcenon::thread::enhanced_cancellation_token::register_callback ( callback_type callback) -> callback_handle
nodiscard

Registers a callback to be invoked on cancellation.

Parameters
callbackFunction to call when cancelled.
Returns
Handle for unregistering the callback.

If already cancelled, the callback is invoked immediately.

Definition at line 356 of file enhanced_cancellation_token.cpp.

358 {
359 std::unique_lock<std::mutex> lock(state_->mutex);
360
361 if (state_->is_cancelled.load(std::memory_order_acquire))
362 {
363 lock.unlock();
364 callback();
365 return 0;
366 }
367
368 callback_handle handle =
369 state_->next_handle.fetch_add(1, std::memory_order_relaxed);
370 state_->simple_callbacks[handle] = std::move(callback);
371 return handle;
372 }
std::size_t callback_handle
Callback handle type for registration management.
@ callback
Call user callback for custom decision.

References kcenon::thread::callback.

◆ register_callback() [2/2]

auto kcenon::thread::enhanced_cancellation_token::register_callback ( callback_with_reason_type callback) -> callback_handle
nodiscard

Registers a callback that receives the cancellation reason.

Parameters
callbackFunction to call with reason when cancelled.
Returns
Handle for unregistering the callback.

If already cancelled, the callback is invoked immediately.

Definition at line 374 of file enhanced_cancellation_token.cpp.

376 {
377 std::unique_lock<std::mutex> lock(state_->mutex);
378
379 if (state_->is_cancelled.load(std::memory_order_acquire))
380 {
381 auto reason = state_->reason;
382 lock.unlock();
383 if (reason)
384 {
385 callback(*reason);
386 }
387 else
388 {
390 "Operation cancelled",
391 std::chrono::steady_clock::now(),
392 std::nullopt});
393 }
394 return 0;
395 }
396
397 callback_handle handle =
398 state_->next_handle.fetch_add(1, std::memory_order_relaxed);
399 state_->reason_callbacks[handle] = std::move(callback);
400 return handle;
401 }

References kcenon::thread::callback, and kcenon::thread::cancellation_reason::user_requested.

◆ remaining_time()

auto kcenon::thread::enhanced_cancellation_token::remaining_time ( ) const -> std::chrono::milliseconds
nodiscard

Gets the remaining time before timeout/deadline.

Returns
Remaining duration, or zero if expired or no timeout.

Definition at line 320 of file enhanced_cancellation_token.cpp.

322 {
323 if (!has_timeout())
324 {
325 return std::chrono::milliseconds::max();
326 }
327
328 auto now = std::chrono::steady_clock::now();
329 auto deadline_point = state_->deadline_point;
330
331 if (now >= deadline_point)
332 {
333 return std::chrono::milliseconds::zero();
334 }
335
336 return std::chrono::duration_cast<std::chrono::milliseconds>(deadline_point -
337 now);
338 }
auto has_timeout() const -> bool
Checks if the token has a timeout or deadline.

References has_timeout(), and state_.

Here is the call graph for this function:

◆ start_timeout_timer()

auto kcenon::thread::enhanced_cancellation_token::start_timeout_timer ( std::weak_ptr< state > state_weak,
std::chrono::steady_clock::time_point deadline ) -> void
staticprivate

Definition at line 444 of file enhanced_cancellation_token.cpp.

447 {
448 std::thread timer_thread(
449 [state_weak, deadline_point]() mutable
450 {
451 auto s = state_weak.lock();
452 // Release the weak_ptr immediately after locking, regardless of
453 // lock success. This ensures ~weak_ptr() runs while the strong
454 // reference (s) is still alive, preventing a data race on the
455 // shared control block between this thread's operator delete
456 // (via __on_zero_shared_weak) and the token destructor's
457 // __release_shared read (ThreadSanitizer: data race).
458 state_weak.reset();
459 if (!s)
460 {
461 return;
462 }
463
464 s->timer_active.store(true, std::memory_order_release);
465
466 std::unique_lock<std::mutex> lock(s->mutex);
467
468 // Wait until deadline or cancellation
469 auto result = s->cv.wait_until(
470 lock, deadline_point,
471 [&s]
472 {
473 return s->is_cancelled.load(std::memory_order_acquire) ||
474 s->timer_should_stop.load(std::memory_order_acquire);
475 });
476
477 // If not cancelled and deadline reached, cancel with timeout reason
478 if (!result && !s->is_cancelled.load(std::memory_order_acquire))
479 {
480 std::vector<callback_type> simple_to_invoke;
481 std::vector<callback_with_reason_type> reason_to_invoke;
482 cancellation_reason new_reason;
483
484 bool was_cancelled =
485 s->is_cancelled.exchange(true, std::memory_order_release);
486 if (!was_cancelled)
487 {
488 new_reason.reason_type = cancellation_reason::type::timeout;
489 new_reason.message = "Timeout expired";
490 new_reason.cancel_time = std::chrono::steady_clock::now();
491 s->reason = new_reason;
492
493 for (auto& [handle, cb] : s->simple_callbacks)
494 {
495 simple_to_invoke.push_back(std::move(cb));
496 }
497 s->simple_callbacks.clear();
498
499 for (auto& [handle, cb] : s->reason_callbacks)
500 {
501 reason_to_invoke.push_back(std::move(cb));
502 }
503 s->reason_callbacks.clear();
504 }
505
506 lock.unlock();
507 s->cv.notify_all();
508
509 for (const auto& cb : simple_to_invoke)
510 {
511 cb();
512 }
513 for (const auto& cb : reason_to_invoke)
514 {
515 cb(new_reason);
516 }
517 }
518 else
519 {
520 lock.unlock();
521 }
522
523 s->timer_active.store(false, std::memory_order_release);
524 });
525
526 timer_thread.detach();
527 }
@ timeout
Timeout duration expired.

References kcenon::thread::cancellation_reason::cancel_time, kcenon::thread::cancellation_reason::message, kcenon::thread::cancellation_reason::reason_type, and kcenon::thread::cancellation_reason::timeout.

◆ unregister_callback()

auto kcenon::thread::enhanced_cancellation_token::unregister_callback ( callback_handle handle) -> void

Unregisters a previously registered callback.

Parameters
handleThe handle returned from register_callback.

Definition at line 403 of file enhanced_cancellation_token.cpp.

405 {
406 if (handle == 0)
407 {
408 return;
409 }
410
411 std::lock_guard<std::mutex> lock(state_->mutex);
412 state_->simple_callbacks.erase(handle);
413 state_->reason_callbacks.erase(handle);
414 }

Referenced by kcenon::thread::cancellation_callback_guard::~cancellation_callback_guard().

Here is the caller graph for this function:

◆ wait()

auto kcenon::thread::enhanced_cancellation_token::wait ( ) const -> void

Waits until the token is cancelled.

Blocks the calling thread until the token is cancelled.

Definition at line 416 of file enhanced_cancellation_token.cpp.

417 {
418 std::unique_lock<std::mutex> lock(state_->mutex);
419 state_->cv.wait(
420 lock, [this]
421 { return state_->is_cancelled.load(std::memory_order_acquire); });
422 }

References state_.

◆ wait_for()

auto kcenon::thread::enhanced_cancellation_token::wait_for ( std::chrono::milliseconds timeout) const -> bool
nodiscard

Waits for cancellation with a timeout.

Parameters
timeoutMaximum time to wait.
Returns
true if cancelled, false if timeout expired.

Definition at line 424 of file enhanced_cancellation_token.cpp.

426 {
427 std::unique_lock<std::mutex> lock(state_->mutex);
428 return state_->cv.wait_for(
429 lock, timeout,
430 [this]
431 { return state_->is_cancelled.load(std::memory_order_acquire); });
432 }

◆ wait_until()

auto kcenon::thread::enhanced_cancellation_token::wait_until ( std::chrono::steady_clock::time_point deadline) const -> bool
nodiscard

Waits for cancellation until a deadline.

Parameters
deadlineMaximum time point to wait until.
Returns
true if cancelled, false if deadline reached.

Definition at line 434 of file enhanced_cancellation_token.cpp.

436 {
437 std::unique_lock<std::mutex> lock(state_->mutex);
438 return state_->cv.wait_until(
439 lock, deadline_point,
440 [this]
441 { return state_->is_cancelled.load(std::memory_order_acquire); });
442 }

Member Data Documentation

◆ state_

std::shared_ptr<state> kcenon::thread::enhanced_cancellation_token::state_
private

The documentation for this class was generated from the following files: