Cpp-Taskflow
2.2.0
|
After you create a task dependency graph, you need to dispatch it to threads for execution. In this chapter, we will show you how to execute a task dependency graph.
Each taskflow object has exactly one graph at a time that represents a set of dependent tasks constructed so far. To execute a graph, you need to create an executor from tf::Executor. An executor manages a set of worker threads and schedules task execution through an efficient work-stealing algorithm. Issuing a call to run a taskflow creates a topology. A topology is a data structure wrapping around a running graph. Each executor object has a list of topologies to keep track of the execution status of running and finished graphs. Users can retrieve this information for graph inspection and debugging.
The first step is to create an executor to run a taskflow. tf::Executor takes an unsigned integer to construct an executor of N
worker threads. The default value is std::thread::hardware_concurrency.
An executor can be reused to execute multiple taskflows. In most workloads, you may need only one executor but multiple taskflows to represent parts of a parallel decomposition.
tf::Executor provides a set of run_*
methods, tf::Executor::run, tf::Executor::run_n, and tf::Executor::run_until to run a taskflow for one time, multiple times, or until a given predicate evaluates to true. All methods accept an optional callback to invoke after the execution completes, and return a std::future for users to access the execution status. The code below shows several ways to run a taskflow.
Debrief:
Issuing multiple runs on a same taskflow will automatically synchronize to a sequential chain of executions following the order of the run calls.
A key point to notice is a running taskflow must remain alive during its execution. It is your responsibility to ensure a taskflow not being destructed when it is running. For example, the code below can result undefined behavior.
Similarly, you should avoid touching a taskflow while it is running.
A rule of thumb is to always keep a taskflow alive in your function scope while it is participating in an execution.