Open
Description
Can someone just give me instructions how to cancel awaitables and what responsabilities does the caller have, i looked up the doc but it was lacking
struct CustomCancel {
asio::cancellation_signal& signal_;
CustomCancel(asio::cancellation_signal& signal) : signal_(signal) {}
void operator()(asio::cancellation_type type = asio::cancellation_type::all) const {
std::cout << "cancelled " << std::endl;
signal_.emit(type);
}
};
template<typename T>
struct Future {
asio::cancellation_signal cancel_sig;
asio::cancellation_slot cl;
std::exception_ptr ex;
bool await_ready() const noexcept { return done_; }
template<typename Promise>
void await_suspend(std::coroutine_handle<Promise> h) noexcept {
//Check if the promise has a cancellation slot and attach a handler if available
if constexpr (requires { h.promise().get_cancellation_slot(); })
if ((cl = h.promise().get_cancellation_slot()).is_connected()) {
cl.emplace<CustomCancel>(cancel_sig);
std::cout << "Emplaced " << std::endl;
}
std::cout << "handle is set" << std::endl;
handle_.reset(h.address());
}
auto await_resume() {
if (cl.is_connected()) {
cl.clear();
}
if (cancel_sig.slot().is_connected()) {
throw std::runtime_error("Operation was cancelled");
}
if (ex) {
std::rethrow_exception(ex);
}
return *value_;
}
template<typename Ty_>
void set_value(Ty_&& value) {
if (!done_ && handle_ && !handle_.done()) {
value_ = value;
done_ = true;
auto h = std::move(handle_);
handle_.reset();
h.resume();
}
else {
throw std::runtime_error("Either no handle or value is set");
}
}
T get_value() const {
if (done_)
return *value_;
else {
throw std::runtime_error("Future value not set");
}
}
bool done() const noexcept {
return done_;
}
void interrupt_await()& {
ex = cobalt::detail::detached_exception();
handle_.release().resume();
}
private:
cobalt::unique_handle<void> handle_ = nullptr;
std::optional<T> value_;
bool done_{ false };
};
Metadata
Metadata
Assignees
Labels
No labels