What is a future exactly and what does it mean to cancel it? In C++ you have std::future
objects which merely provide storage for the result of an asynchronous task, and some way to wait for that task to finish. You can just let the std::future
object go out of scope without waiting for its result, but that doesn't cancel the task itself.
If you mean "why can many languages' asynchronous tasks not be canceled?", then again you have to first discuss what a task exactly is. I'll simplify and say there's basically two types: threads and coroutines.
Threads run independent from the main thread. Just cancelling them from the outside is hard, because it is difficult or impossible to predict what that thread is doing at the time it is being cancelled. Maybe it was just locking a mutex? Or it opened a file? You have to ensure that atomic actions are completed, and that any resources that are in use are released correctly. That might require unwinding the stack (as if an exception was thrown). POSIX threads can be cancelled, but only at cancellation points; C++11 threads don't even bother and don't provide a way to cancel them.
Coroutines are easier to cancel, as there are natural cancellation points from the language itself: every time await
or yield
is used. They also often run in the same thread, so there are much less thread-safety issues to worry about. For stackless coroutines like in C++20, a coroutine's state is stored in something that is just a class
, with that state being stored in member variables. Since destroying objects is well-defined in most languages, destroying an object of that class is easy as well. So in C++ you can just cancel a coroutine by letting the object that stores its state (like C++23's std::generator
) go out of scope.
So in summary: future ≠ task, and whether cancellation is possible depends on the nature of the task. I've also simplified here, there are many variations on threads and coroutines, each with their own implementation details, so you have to look into your language's implementation to find out why cancellation is possible or not.
drop
ping the future, so you don't need a separate interface for that. $\endgroup$