Foundations
Job systems and worker pools
An engine has many small tasks that can run beside the frame: decode an image, build a mesh's LODs, transcode a texture. Starting a thread for each one does not scale. A job system runs them as jobs on a few worker threads that take them from a queue. This page explains how: the pool and its queue, splitting work into jobs, waiting without blocking a worker, holding jobs back when memory runs out, order, cancel and shutdown, and results that do not depend on the order. The last part shows how RASM loads assets with it.
In short
- A pool has a fixed number of worker threads, about one per core that the program does not use for other work. A queue holds the jobs that wait.
- A big task is split into child jobs (one per image, one per mesh part), so it runs on every free core at once.
- A job must never wait for another job: with all workers waiting, nobody runs the jobs they wait for. Use a counter: the child that finishes last runs what comes next (a continuation).
- Results that wait for the main thread take memory. A budget lets a job start only when its bytes fit: jobs wait in the queue as a few bytes, not in memory as decoded data. This is backpressure.
- Children run before new top-level jobs, so started work ends first. A priority is a sort key of the queue.
- A ticket per task lets the caller cancel it: a queued job is skipped, a running one gives its result up. Shutdown drops the queue and joins the threads.
- Each job writes only its own output, so the result is the same in any order.
1The problem: one thread per task
The simple way to run a task in the background is a new thread, or a library task like std::async, per task. That is fine for three tasks. Look at 300 of them on a machine with 4 cores.
More threads than cores
The OS switches between them. Each switch costs time and fills the caches with another thread's data. The work does not end sooner.
All the memory at once
Every running task holds its file and its decoded data. 300 decoded images of 21 MiB each need over 6 GiB at the same time.
No order, no cancel
Started threads all run. A near object cannot go first, and a task the program no longer needs still runs to the end.
2A pool and a queue
A worker pool starts a fixed number of threads once. Each worker runs a loop: take a job from the queue, run it, take the next. When the queue is empty, it sleeps until a new job arrives. A job is just a function to call, with the data it needs copied in.
How many workers? The pool should fill the cores that are free, and no more:
workers = hardware threads − busy threads
- hardware threads
- what the OS reports (std::thread::hardware_concurrency); with hyper-threading, two per core
- busy threads
- at least the main thread, which records the frames; a game may add physics, audio or its own jobs
A worker that reads a file waits for the disk part of the time, and the core is free then. Some pools have a few more workers than cores for that, or a separate thread for file reads. Decoding is pure CPU work, so for decode-heavy jobs, one worker per free core is right.
3Split big tasks into jobs
One task can be big: a model file with 15 images, where each image needs a decode and a mip chain. As one job, it runs on one core while the others sleep. Split it: the job reads the file, then makes one child job per image. The children run on every free worker.
What makes a good job? It is big enough that the queue's lock is a small part of it (a decode of 10 ms, not one pixel), and it does not touch what other running jobs write.
4Never wait inside a job
After the children, the model still has work to do: put the results together and hand them over. The obvious code waits for the children inside the parent job. That blocks a worker. With one worker, it waits forever.
The parent waits for its children
With N workers, N parents that wait at once stop the pool just the same. A bigger pool only makes it rarer.
The last child runs what comes next
The counter is atomic. The child that sees it go from 1 to 0 is the last one, so all the others are done and their results are written.
Click through the counter on a pool of one worker.
1. The parent splits the work
The parent does not wait. It only leaves a counter and three jobs.
2. Children run and count down
Each child writes only its own result, then counts down. The order does not matter.
3. The last child finishes the task
This is a continuation: the next step is attached to the work it depends on, instead of a thread that waits for it.
Two other ways out are common:
Continuation
A counter per task. Needs no help from the pool, and works with any number of workers.
Cost: the next step is a function, not the rest of the parent's code
Help while waiting
The wait call runs jobs from the queue until its own are done. The code reads top to bottom.
Cost: a deep call stack; it may pick up a long, unrelated job
Fibers
A waiting job's stack is parked and the worker takes another job, like Naughty Dog's engine. Waits look normal.
Cost: platform code, care with thread-local data
5Backpressure: a memory budget
Workers decode faster than the main thread can upload. A frame uploads a few textures, but 23 workers decode 23 at once. The decoded results pile up and wait, each one many MiB. Backpressure pushes back on the producer: a job starts only when its bytes fit in a budget.
start the next job if held + its bytes ≤ budget, or held = 0
- held
- the bytes of the jobs that run, plus the results that wait for the main thread to use them
- its bytes
- an estimate, from the file's header: a 2048 × 2048 RGBA image with its mips is 21.3 MiB
- held = 0
- a job bigger than the whole budget still runs, alone, or it would never run
A job that does not fit stays in the queue. There it is a file name: a few bytes, not 21 MiB. The main thread gives bytes back when it has used a result, and the next jobs start. Try it: 24 images of different sizes, decoded by the workers, uploaded by the main thread at 32 MiB per frame.
No budget
Fastest when memory is plenty. The peak is all the results that finish before the main thread takes them.
A budget above what one frame uploads
The workers stay a little ahead of the main thread. The peak is the budget; the time hardly grows.
A budget too small
Workers wait for the main thread most of the time. Memory is low, but the loads take longer.
- A job that waits for the budget inside the job
- It blocks a worker, and with every worker blocked, nothing gives bytes back: the same deadlock as section 4. Check the budget in the queue, before the job starts.
- Child jobs held back by the budget
- A parent already holds its bytes, and its children need to run to give them back. Do not gate children; count their bytes in the parent's estimate.
- The main thread waits for a job behind the budget
- A loading screen that waits for one load while results sit unused never frees the budget. Before each wait, use what is ready.
6Order and priority
FIFO
Jobs run in the order they were asked for. Simple and fair: nothing waits forever.
Children first
A started task finishes before new ones start, so its memory goes soon, and its result arrives early.
Priority
A sort key per job: the distance to the camera, or "visible now". The queue becomes sorted, and the key can change while the job waits.
Watch: a low job can wait forever; age raises its key
7Workers below the main thread
The main thread wakes a worker when it queues a job. On Windows a thread that wakes gets a short boost above its priority. If the worker runs at the main thread's priority, the boost puts it above, and it can take the main thread's own core: the main thread then waits inside notify_all for the whole job.
Worker at the main thread's priority
Worker one level below
A lower priority does not slow a worker on a free core: it only loses a core that a higher thread wants. Linux has the same idea in a thread's nice value, macOS in a relative priority inside a QoS class.
8Cancel and shut down
A map viewer scrolls: tiles it asked for a second ago are off screen now. Their jobs should not run, or at least their results should not be used. Each task gets a small shared ticket: a "cancelled" flag, and a state that says who owns the result.
Queued
The worker sees the flag when it reaches the job and drops it. It never started, so it holds no bytes of the budget.
Running
A job cannot be stopped from outside. It checks the flag between its steps and skips the rest, then ends as usual.
Done
The result is already there. Cancel frees it at once and gives its bytes back.
Shutdown is a cancel of everything, in this order:
- cancelSet every ticket's flag, so running jobs skip their next steps.
- stopSet the pool's stop flag and empty the queue; jobs pushed now are dropped.
- wakeWake every sleeping worker, so it sees the stop flag.
- joinWait for each thread to end. Only then free what the jobs use.
If a job keeps a pointer to the engine and the engine is destroyed first, the job writes freed memory. Give a job its own data, shared with the main thread by reference count, and join the workers before anything they read goes.
9The same result in any order
The workers finish in a different order on every run, and on every machine. The result must not change: the tests compare images to the pixel. The rule: each job writes only its own output, made from its own input.
Jobs append to one list
The order follows the schedule. A shared sum of floats changes in its last bits too, since float addition depends on order.
Each job has its own slot
The slots are made before the jobs start, so no job changes the list itself. The finish step reads them in a fixed order.
The log: two jobs that print at the same time print in any order. Timings, of course. Neither changes a pixel.
10In RASM
The engine owns one WorkerPool. Every loadMesh, loadTexture and loadEnvironment is a load job on it; a glTF import splits into a child job per image and per sub-mesh's LODs. The main thread picks up done loads in finishLoads (streaming assets).
Where RASM follows the page, and where it differs
| Part | This page | RASM |
|---|---|---|
| Workers | hardware threads minus the busy ones | EngineConfig::loadThreads; 0 (the default) takes std::thread::hardware_concurrency minus one, for the main thread, at least 1. A game with threads of its own sets fewer. The pool starts first in the Engine constructor. |
| Priority | workers below the main thread | Each WorkerPool thread calls lowerThreadPriority when it starts. The same pool class runs the shader workers of the ShaderCompiler, named RASM shaders N (Shader warm-up). |
| Queue | FIFO, children first, priority | Two FIFO queues of std::function jobs under one mutex: pushChild, and push (pushNext puts a started load's next step at the front); children are taken first. No priority yet: it would be a sort key of the load queue. |
| Split | a child job per part | spawnMeshChildJobs pushes a runImageWork job per image (decode once, mips per kind of slot, or a KTX2 transcode per format) and a buildMeshLods job per sub-mesh. |
| Waiting | continuation, help, fibers | Continuation: MeshLoadJob::remaining, and the last child runs completeMeshLoad. The main thread's waitForLoads finishes what is ready, then sleeps in waitForCompletion until another load ends. |
| Budget | a job starts if its bytes fit, or nothing is held | EngineConfig::loadMemoryBudget, 512 MiB. Estimates from headers; a mesh starts with its file size; after the parse it holds its geometry and its images' file bytes, and its decoded images are a next step (pushNext, first in the load queue) that waits for the budget too, never held back by the load's own bytes. When the main thread has used a result, a worker frees it, and its bytes go back once it is freed (AssetLoader::Impl::freeOnWorker, see heap memory in the frame); a glTF texture's levels keep their share until that texture is filled. Children are not gated. |
| Cancel | ticket: flag and state | LoadTicket: cancelled, state (RUNNING, DONE, DROPPED), bytes. destroyMesh, destroyTexture and destroyEnvironment call dropLoad (through AssetLoader::Impl::dropPendingLoad) and erase the pending entry at once. For a finished load, dropLoad returns its bytes, which go back once a worker has freed the result. |
| Shutdown | cancel, stop, wake, join | ~AssetLoader drops every pending load, then WorkerPool::shutdown empties the queues and joins the threads, before anything else is destroyed. |
| Same result | each job its own slot | The plan makes every GltfImageTarget's empty TextureRaw before the jobs start, already in GLTFRaw::ktxImages or imageLevels; a LOD job writes only its own sub-mesh. The images and examples are the same as with one thread. |
Measured
python tools/load_bench.py: Release, headless, RTX 3060, i7-13700KF (24 hardware threads, so 23 workers), the median of three runs, before and after the pool.
The main thread does the same work, so the longest frame while a model loads stays about the same (5 to 9 ms); Sponza's is sometimes up to 16 ms, because 23 busy workers and the driver leave the main thread less of the CPU (P25). The burst (17_streaming --burst) ends in 453 ms against 501, and its longest frame is 22.2 ms against 37.2. On Windows the old std::async used the system's thread pool, so it had 44 threads at most, not 300; libc++ on macOS starts one thread per call.
Where it lives in code
| What | Where |
|---|---|
| The pool, tickets | WorkerPool, WorkerJob, LoadTicket in src/core/workerPool.h, src/core/workerPool.cpp |
| A load's shared data | MeshLoadJob, TextureLoadJob, EnvironmentLoadJob in src/assets/loadJobs.h |
| Mesh load jobs | runMeshImport, endMeshChildJob, completeMeshLoad, AssetLoader::Impl::loadMesh in src/assets/meshLoad.cpp |
| Image jobs | parseMeshFile, runImageWork, finishImageWork, GltfImageWork in src/assets/meshImport.cpp |
| Texture and environment jobs | AssetLoader::Impl::loadTexture in src/assets/textureLoad.cpp; AssetLoader::Impl::loadEnvironment in src/assets/environmentLoad.cpp; a destroyed object's load is dropped by AssetLoader::Impl::forget, which the renderer calls through LoadHooks |
| Pick-up, budget give-back, shutdown | finishLoads, finishReadyLoads, getLoadStats, dropAll (from ~AssetLoader) in src/assets/assetLoader.cpp |
| Settings and stats | AssetLoaderConfig::loadThreads, loadMemoryBudget (also in EngineConfig), LoadStats in include/rasm/types.h; the RASM window's Loads line |
| Tests | tests/workerPoolTests.cpp: order, children first, one worker with nested children, cancel, budget, shutdown |
| Examples, numbers | examples/17_streaming (--burst), examples/10_ktx2_textures (--measure), tools/load_bench.py |
| API | getLoadStats, LoadStats, EngineConfig |
- No job waits for another job, or for the budget. Split, count down, and let the last one go on.
- A job holds its load's data by
shared_ptrand never the engine, the registry or the device. - Every byte a load takes from the budget goes back once: what the main thread used or dropped while
DONEgoes back from the worker that frees it; the job gives back what it held when it endsDROPPED. - Each job writes only its own output, made before the jobs start; the finish step reads in a fixed order.
- A running job checks its ticket between steps, and every child still counts down when it skips its work.
- The basis transcoder's first use runs alone (
decodeKtx): libktx sets up its tables then, with no lock.
No priority per load: the load queue is FIFO. Files are read by the same workers that decode. The workers run at the main thread's priority, so a full pool can stretch a frame (P25). A load's steps on the main thread are not split (P24).
Further reading
- Christian Gyrling, Parallelizing the Naughty Dog Engine Using Fibers, GDC 2015: jobs, counters and fibers for a whole engine.
- Jason Gregory, Game Engine Architecture, 3rd edition: the chapter on parallelism and concurrent programming.
- Anthony Williams, C++ Concurrency in Action, 2nd edition: thread pools, atomics and memory order.
- Sean Parent, Better Code: Concurrency, 2016: tasks without waits, and continuations.
- Streaming assets in the background, Texture uploads, Deferred destruction.