TExcelTAD
Home › Game Engine Architecture in C++ › Task Graphs and Dependencies

Task Graphs and Dependencies

A job system runs independent work in parallel. But a frame is not a bag of independent work: animation must finish before skinning, physics before the transform update, the transform update before culling. Calling wait() between every pair of steps works, but it leaves cores idle whenever one step is short. A task graph describes the frame as tasks plus "must run after" edges, and the scheduler starts each task as soon as everything it depends on is done.

text
   input ──► gameplay ──► physics ──► transforms ──► culling ──► render
                 │                        ▲
                 └──► animation ──► skinning ┘        audio (independent)

Topological order and waves

A valid run order is a topological sort of the graph: every task appears after all of its dependencies. Kahn's algorithm finds one by repeatedly taking tasks with no unfinished dependencies. If we take all such tasks at once, we get waves: every task in a wave can run in parallel. If some tasks never become ready, the graph has a cycle and no order exists.

cpp · try it yourself
#include <iostream>
#include <string>
#include <thread>
#include <vector>

struct Task {
    std::string name;
    std::vector<int> deps;     // indices of tasks that must finish first
};

// Kahn's algorithm, grouped into waves. Returns an empty list if there is a cycle.
std::vector<std::vector<int>> buildWaves(const std::vector<Task>& tasks) {
    int n = int(tasks.size());
    std::vector<int> missing(n);
    std::vector<std::vector<int>> dependents(n);
    for (int i = 0; i < n; i++) {
        missing[i] = int(tasks[i].deps.size());
        for (int d : tasks[i].deps) dependents[d].push_back(i);
    }
    std::vector<std::vector<int>> waves;
    std::vector<int> ready;
    for (int i = 0; i < n; i++) if (missing[i] == 0) ready.push_back(i);
    int scheduled = 0;
    while (!ready.empty()) {
        waves.push_back(ready);
        scheduled += int(ready.size());
        std::vector<int> next;
        for (int t : ready)
            for (int d : dependents[t])
                if (--missing[d] == 0) next.push_back(d);
        ready = next;
    }
    if (scheduled != n) return {};
    return waves;
}

int main() {
    enum { Input, Gameplay, Animation, Physics, Skinning, Transforms, Culling, Audio, Render };
    std::vector<Task> frame = {
        {"input", {}},
        {"gameplay", {Input}},
        {"animation", {Gameplay}},
        {"physics", {Gameplay}},
        {"skinning", {Animation}},
        {"transforms", {Physics, Skinning}},
        {"culling", {Transforms}},
        {"audio", {}},
        {"render", {Culling, Audio}},
    };

    auto waves = buildWaves(frame);
    std::vector<int> finishedWave(frame.size(), -1);
    for (std::size_t w = 0; w < waves.size(); w++) {
        std::cout << "wave " << w << ":";
        for (int t : waves[w]) std::cout << " " << frame[t].name;
        std::cout << "\n";
        // Run the whole wave in parallel; each task writes only its own slot.
        std::vector<std::thread> threads;
        for (int t : waves[w]) threads.emplace_back([&, t, w] { finishedWave[t] = int(w); });
        for (auto& th : threads) th.join();
    }

    // Check every dependency finished in an earlier wave.
    bool ok = true;
    for (std::size_t t = 0; t < frame.size(); t++)
        for (int d : frame[t].deps) ok = ok && finishedWave[d] < finishedWave[t];
    std::cout << "dependencies respected: " << (ok ? "yes" : "no") << "\n";

    frame[Input].deps.push_back(Render);      // a mistake: input waits for render
    std::cout << "with a cycle: " << (buildWaves(frame).empty() ? "rejected" : "accepted") << "\n";
}
wave 0: input audio
wave 1: gameplay
wave 2: animation physics
wave 3: skinning
wave 4: transforms
wave 5: culling
wave 6: render
dependencies respected: yes
with a cycle: rejected

Nine tasks fit in seven waves: audio runs in wave 0 alongside input, and animation and physics share wave 2. The critical path, the longest chain of dependencies, sets the minimum frame time no matter how many cores you have.

Note: Waves are a simplification. A real scheduler doesn't wait for the whole wave to finish: the moment animation completes, skinning can start, even if physics (same wave) is still running. Each task keeps an atomic "dependencies remaining" counter; the last dependency to finish decrements it to zero and pushes the task to the job queue.

Deriving edges from reads and writes

Writing edges by hand is error-prone: someone adds a system that writes Transform and forgets that culling reads it. Engines (Unity's job dependencies, Bevy's scheduler, many ECS frameworks) instead let each task declare the data it reads and writes, and derive the edges in declaration order:

  • write after write or read after write on the same resource: the later task depends on the earlier one;
  • write after read: the writer must wait for earlier readers to finish;
  • read after read: no edge, they can run in parallel.
cpp · try it yourself
#include <algorithm>
#include <iostream>
#include <set>
#include <string>
#include <vector>

struct SystemDecl {
    std::string name;
    std::set<std::string> reads, writes;
};

bool touches(const std::set<std::string>& a, const std::set<std::string>& b) {
    for (auto& x : a) if (b.count(x)) return true;
    return false;
}

int main() {
    std::vector<SystemDecl> systems = {
        {"playerInput", {"Input"}, {"Velocity"}},
        {"aiSteering", {"Position"}, {"Velocity"}},
        {"integrate", {"Velocity"}, {"Position"}},
        {"animation", {"AnimState"}, {"Pose"}},
        {"cameraFollow", {"Position"}, {"Camera"}},
        {"buildDrawList", {"Position", "Pose", "Camera"}, {"DrawList"}},
    };

    std::vector<std::vector<int>> deps(systems.size());
    for (std::size_t later = 0; later < systems.size(); later++) {
        for (std::size_t earlier = 0; earlier < later; earlier++) {
            const auto& a = systems[earlier];
            const auto& b = systems[later];
            bool conflict = touches(b.writes, a.writes)    // write after write
                         || touches(b.reads, a.writes)     // read after write
                         || touches(b.writes, a.reads);    // write after read
            if (conflict) deps[later].push_back(int(earlier));
        }
    }

    // Longest-path level = the earliest wave each system can run in.
    std::vector<int> level(systems.size(), 0);
    for (std::size_t i = 0; i < systems.size(); i++) {
        std::cout << systems[i].name << " after:";
        if (deps[i].empty()) std::cout << " (nothing)";
        for (int d : deps[i]) { std::cout << " " << systems[d].name; level[i] = std::max(level[i], level[d] + 1); }
        std::cout << "  -> wave " << level[i] << "\n";
    }
}
playerInput after: (nothing)  -> wave 0
aiSteering after: playerInput  -> wave 1
integrate after: playerInput aiSteering  -> wave 2
animation after: (nothing)  -> wave 0
cameraFollow after: integrate  -> wave 3
buildDrawList after: integrate animation cameraFollow  -> wave 4

playerInput and aiSteering both write Velocity, so they are serialized. animation touches none of the movement data, so it lands in wave 0 next to playerInput. cameraFollow and aiSteering both only read Position, so there is no edge between them; cameraFollow waits for integrate alone, because integrate writes the Position it reads. Declaring access precisely is what buys parallelism: if cameraFollow declared a write to Position "just in case", it would also have to wait for every earlier reader.

Tip: Make the declared access the only way a system can reach its data (pass it views built from the declaration). If code can grab any component through a global, the scheduler's picture is wrong and you get rare, unreproducible races.

In practice

  • Build the graph once (or when systems are added), not every frame. Executing a prebuilt graph is cheap.
  • Visualize it. Dump the graph in Graphviz dot format from a debug command; a picture shows accidental serialization at a glance.
  • Libraries: Taskflow (C++17 task graphs), enkiTS (dependencies between task sets), Unreal's UE::Tasks with prerequisites, Unity's JobHandle dependencies.
  • The same idea applied to GPU passes is a render graph.

Test yourself

What does it mean if Kahn's algorithm cannot schedule every task?

  1. The graph has too many tasks
  2. The graph contains a dependency cycle
  3. Two tasks read the same data
  4. Some tasks have no dependencies

Two systems both only read Position. Which edge does the read/write rule create between them?

  1. The later one depends on the earlier one
  2. The earlier one depends on the later one
  3. No edge; they can run in parallel
  4. A cycle

What limits the shortest possible frame time of a task graph, even with unlimited cores?

  1. The number of tasks
  2. The critical path: the longest chain of dependent tasks
  3. The size of the job queue
  4. The number of waves without dependencies