Taskflow
2.7.0
|
It is very common for a parallel program to spawn task dependency graphs at runtime. In Taskflow, we call this dynamic tasking.
Dynamic tasks are those created during the execution of a graph. These tasks are spawned from a parent task and are grouped together to a subflow dependency graph. Taskflow has an unified interface for static and dynamic tasking. To create a subflow, emplace a callable that takes an argument of type tf::Subflow. A tf::Subflow object will be created and forwarded to the execution context of the task. All methods you find in tf::Taskflow are applicable for tf::Subflow.
Debrief:
Line 8-14 is the main block to enable dynamic tasking. Taskflow uses a std::variant date type to unify the interface of static tasking and dynamic tasking. The runtime will create a tf::Subflow passing it to task B, and spawn a dependency graph as described by the associated callable. This new subflow graph will be added to the topology of its parent task B. Due to the property of dynamic tasking, we cannot dump its structure before execution. We will need to run the graph first to spawn the graph and then call tf::Taskflow::dump.
By default, a subflow joins its parent task when the program leaves its execution context. All nodes of zero outgoing edges in the subflow precede its parent task. You can explicitly join a subflow within its execution context to carry out recursive patterns. A famous implementation is fibonacci recursion.
The code above computes the 10th fibonacci number using recursive subflow. Calling tf::Subflow::join immediately materializes the subflow by executing all associated tasks to recursively compute fibonacci numbers. The taskflow graph is shown below:
Our implementation to join subflows is recursive in order to preserve the thread context in each subflow task. Having a deep recursion of subflows may cause stack overflow.
In contract to joined subflow, you can detach a subflow from its parent task, allowing its execution to flow independently.
The figure below demonstrates a detached subflow based on the previous example. A detached subflow will eventually join the topology of its parent task.
Detached subflow becomes an independent graph attached to the top-most taskflow. Running a taskflow multiple times will accumulate all detached tasks in the graph. For example, running the above taskflow 10 times results in a total of 34 tasks.
The dumped graph is shown as follows:
A subflow can be nested or recursive. You can create another subflow from the execution of a subflow and so on.
Debrief:
Similarly, you can detach a nested subflow from its parent subflow. A detached subflow will run independently and eventually join the topology of its parent subflow.