Job Systems
Every CPU a game ships on has several cores, and a frame that runs everything on one thread leaves most of them idle. Spawning a std::thread per task is far too slow (creating a thread costs tens of microseconds, and the OS can't run hundreds of them at once anyway). Engines instead start a fixed set of worker threads once, at startup, and feed them small units of work called jobs.
main thread job queue workers (one per core, minus one)
─────────── ───────── ─────────────────────────────────
submit(animate chunk 0..3) ───► [ job | job | job | job ] ──► worker 1: pop, run, pop, run...
submit(cull chunk 0..7) ───► [ job | job | ... ] ──► worker 2: pop, run, ...
wait(counter) ◄────────────────── counter reaches 0 ◄────────── each finished job decrements itThe C++ standard library gives you the pieces: std::thread, std::mutex, std::condition_variable and std::atomic. If threads, mutexes and lambdas are new to you, review the C++ course first, especially Lambdas.
A minimal job system
The pool below has a queue protected by a mutex, a condition variable that wakes sleeping workers, and a counter per batch. wait blocks until the batch's counter drops to zero. Results go into a vector slot per job index, so the output never depends on which worker ran which job.
#include <atomic>
#include <condition_variable>
#include <cstdint>
#include <functional>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
class JobSystem {
public:
struct Counter { std::atomic<int> remaining{0}; };
explicit JobSystem(int workers) {
for (int i = 0; i < workers; i++) threads_.emplace_back([this] { workerLoop(); });
}
~JobSystem() {
{ std::lock_guard lock(mutex_); stopping_ = true; }
wake_.notify_all();
for (auto& t : threads_) t.join();
}
void submit(std::function<void()> job, Counter& counter) {
counter.remaining.fetch_add(1);
{ std::lock_guard lock(mutex_); queue_.push({std::move(job), &counter}); }
wake_.notify_one();
}
// Wait for a counter; the waiting thread helps by running queued jobs instead of sleeping.
void wait(Counter& counter) {
while (counter.remaining.load() > 0) {
if (!runOne()) std::this_thread::yield();
}
}
private:
struct Job { std::function<void()> fn; Counter* counter; };
bool runOne() {
Job job;
{
std::lock_guard lock(mutex_);
if (queue_.empty()) return false;
job = std::move(queue_.front());
queue_.pop();
}
job.fn();
job.counter->remaining.fetch_sub(1);
return true;
}
void workerLoop() {
for (;;) {
Job job;
{
std::unique_lock lock(mutex_);
wake_.wait(lock, [this] { return stopping_ || !queue_.empty(); });
if (stopping_ && queue_.empty()) return;
job = std::move(queue_.front());
queue_.pop();
}
job.fn();
job.counter->remaining.fetch_sub(1);
}
}
std::vector<std::thread> threads_;
std::queue<Job> queue_;
std::mutex mutex_;
std::condition_variable wake_;
bool stopping_ = false;
};
int main() {
JobSystem jobs(3);
// Pretend work: each job sums the squares of its chunk of entity IDs.
const int kEntities = 1000, kChunk = 250;
std::vector<std::int64_t> partial(kEntities / kChunk, 0);
JobSystem::Counter done;
for (int c = 0; c < kEntities / kChunk; c++) {
jobs.submit([c, &partial] {
std::int64_t sum = 0;
for (int i = c * kChunk; i < (c + 1) * kChunk; i++) sum += std::int64_t(i) * i;
partial[c] = sum; // each job writes only its own slot
}, done);
}
jobs.wait(done);
std::int64_t total = 0;
for (std::size_t c = 0; c < partial.size(); c++) {
std::cout << "chunk " << c << ": " << partial[c] << "\n";
total += partial[c];
}
std::cout << "total: " << total << "\n";
}chunk 0: 5177125
chunk 1: 36364625
chunk 2: 98802125
chunk 3: 192489625
total: 332833500
Three rules make the result deterministic even though the workers interleave differently on every run:
- Each job writes only its own output slot (
partial[c]). No two jobs touch the same memory, so no locks are needed for the data. - Combine results after
wait, on one thread, in index order. - Never print from inside a job. The order would change between runs.
Note:
waitdoesn't just sleep: it pops and runs jobs itself. This matters when a job submits sub-jobs and waits for them; if waiting threads only slept, every worker could end up blocked waiting and nobody would run the jobs they wait for (a deadlock).
parallel_for
Most engine jobs are "do this to N items". A parallelFor helper splits a range into chunks, submits one job per chunk and waits. Picking the chunk size is the main tuning knob: too small and queue overhead dominates, too large and some cores sit idle at the end.
#include <algorithm>
#include <cmath>
#include <functional>
#include <iomanip>
#include <iostream>
#include <thread>
#include <vector>
// A simpler fork-join version: one thread per chunk group, joined at the end.
void parallelFor(int count, int chunk, int threads, const std::function<void(int, int)>& body) {
std::vector<std::thread> pool;
int chunks = (count + chunk - 1) / chunk;
for (int t = 0; t < threads; t++) {
pool.emplace_back([=, &body] {
for (int c = t; c < chunks; c += threads) // static round-robin assignment
body(c * chunk, std::min(count, (c + 1) * chunk));
});
}
for (auto& th : pool) th.join();
}
struct Particle { float x, y, vx, vy; };
int main() {
std::vector<Particle> particles(10000);
for (int i = 0; i < int(particles.size()); i++)
particles[i] = {0.0f, 10.0f, float(i % 7) - 3.0f, float(i % 5)};
const float dt = 1.0f / 60.0f, gravity = -9.81f;
for (int frame = 0; frame < 60; frame++) {
parallelFor(int(particles.size()), 1024, 4, [&](int begin, int end) {
for (int i = begin; i < end; i++) {
Particle& p = particles[i];
p.vy += gravity * dt;
p.x += p.vx * dt;
p.y += p.vy * dt;
}
});
}
double sumY = 0;
for (const Particle& p : particles) sumY += p.y;
std::cout << std::fixed << std::setprecision(4)
<< "particle 0: (" << particles[0].x << ", " << particles[0].y << ")\n"
<< "particle 9: (" << particles[9].x << ", " << particles[9].y << ")\n"
<< "average y: " << sumY / particles.size() << "\n";
}particle 0: (-3.0000, 5.0133)
particle 9: (-1.0000, 9.0132)
average y: 7.0132
Each particle is updated by exactly one thread with exactly the same arithmetic, so the floats come out bit-identical however the chunks are scheduled. (A parallel sum is different: adding floats in a different order changes the last bits. Sum per chunk, then combine in chunk order, as in the first example.)
What real job systems add
| Feature | Why |
|---|---|
| One queue per worker + work stealing | less contention on a single mutex; idle workers steal from busy ones |
| Fibers (Naughty Dog's GDC 2015 talk) | a waiting job can suspend itself and let the worker run something else |
| Priorities | streaming and audio jobs must not starve behind a batch of AI jobs |
| Main-thread-only jobs | some APIs (windowing, many graphics calls) must run on the main thread |
| Dependencies | "run skinning after animation" without a manual wait: see Task Graphs |
Tip: Don't write your own for production unless you have to. enkiTS, Intel oneTBB, Taskflow and the job systems inside Jolt, Unreal (
TaskGraph/UE::Tasks) and Unity (C# Job System) are battle-tested. Writing a small one, as above, is still the best way to understand what they do.
Profile before and after you parallelize. Threading only helps work that is big enough and independent enough; a job that takes 2 µs costs more in queue traffic than it saves. See Profiling: Scopes and Tracy.
Test yourself
Why do engines use a fixed pool of worker threads instead of a new std::thread per task?
- std::thread cannot run lambdas
- Creating threads is expensive and too many threads compete for the same cores
- Worker threads use less memory per job
- The OS forbids more than one thread per core
How does the first example keep its printed results deterministic?
- It locks the console
- Each job writes its own slot and results are combined in index order after wait
- It runs every job on the main thread
- It sleeps between jobs
Why does wait run queued jobs itself instead of only sleeping?
- To print progress
- To avoid deadlock when jobs wait on sub-jobs and every worker is blocked
- Because condition variables are unreliable
- To lower memory usage