30class cancellation_token {
72 auto new_state_weak = std::weak_ptr<token_state>(new_token.state_);
74 for (
const auto& token : tokens) {
75 auto token_copy = token;
76 token_copy.register_callback([new_state_weak]() {
77 if (
auto state = new_state_weak.lock()) {
79 std::vector<std::function<void()>> callbacks_to_invoke;
82 std::lock_guard<std::mutex> lock(state->callback_mutex);
83 bool was_cancelled = state->is_cancelled.exchange(
true);
85 callbacks_to_invoke = std::move(state->callbacks);
86 state->callbacks.clear();
90 for (
const auto&
callback : callbacks_to_invoke) {
108 std::vector<std::function<void()>> callbacks_to_invoke;
111 std::lock_guard<std::mutex> lock(
state_->callback_mutex);
112 bool was_cancelled =
state_->is_cancelled.exchange(
true);
113 if (!was_cancelled) {
115 callbacks_to_invoke = std::move(
state_->callbacks);
116 state_->callbacks.clear();
121 for (
const auto&
callback : callbacks_to_invoke) {
131 return state_->is_cancelled.load();
155 std::unique_lock<std::mutex> lock(
state_->callback_mutex);
158 if (
state_->is_cancelled.load()) {
Provides a mechanism for cooperative cancellation of operations.
cancellation_token(std::shared_ptr< token_state > state)
cancellation_token(cancellation_token &&)=default
common::VoidResult check_cancelled() const
Checks if the token has been canceled and returns an error result.
void cancel()
Cancels the operation.
void register_callback(std::function< void()> callback)
Registers a callback to be invoked when the token is canceled.
cancellation_token(const cancellation_token &)=default
static cancellation_token create_linked(std::initializer_list< cancellation_token > tokens)
Creates a linked token that is canceled when any of the parent tokens are canceled.
static cancellation_token create()
Creates a new cancellation token.
cancellation_token & operator=(cancellation_token &&)=default
bool is_cancelled() const
Checks if the token has been canceled.
cancellation_token & operator=(const cancellation_token &)=default
std::shared_ptr< token_state > state_
@ callback
Call user callback for custom decision.
Error codes and utilities for the thread system.
Core threading foundation of the thread system library.
common::VoidResult make_error_result(error_code code, const std::string &message="")
Create a common::VoidResult error from a thread::error_code.
std::atomic< bool > is_cancelled
std::mutex callback_mutex
std::vector< std::function< void()> > callbacks