![]() |
Taskflow
3.2.0-Master-Branch
|
This chapters discusses how to cancel submitted tasks.
When you submit a taskflow to an executor (e.g., tf::Executor::run), the executor returns a tf::Future object that will hold the result of the execution. tf::Future is a derived class from std::future. In addition to base methods of std::future, you can call tf::Future::cancel to cancel the execution of a running taskflow. The following example cancels a submission of a taskflow that contains 1000 tasks each running one second.
When you request a cancellation, the executor will stop scheduling the rest tasks of the taskflow. Tasks that are already running will continue to finish, but their successor tasks will not be scheduled to run. A cancellation is considered complete when all these running tasks finish. To wait for a cancellation to complete, you may explicitly call tf::Future::get
.
For instance, the following code results in undefined behavior:
The undefined behavior problem exists because tf::Future::cancel does not guarantee an immediate cancellation. To fix the problem, call get
to ensure the cancellation completes before the end of the scope destroys the taskflow.
You can cancel submitted asynchronous tasks using tf::Future::cancel. The following example launches 10000 asynchronous tasks through an executor, acquires their futures, and cancel all of them.
Similar to cancelling a running taskflow, cancelling a submitted asynchronous task does not guarantee the execution will be cancelled. The result depends on the present available workers and whether the asynchronous task is being run by a worker. To wait for a cancellation to complete, you may explicitly call tf::Future::get
. The result may be a std::nullopt if that asynchronous task does not run.
Canceling the execution of a running taskflow has the following limitations:
We may overcome these limitations in the future releases.