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.

CPU work: a thread, a job memory: decoded data, results wrong: blocked, over the limit

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.

300 threads 4 cores switch between them all 300 hold their memory until the end each slice is another thread: switching, cold caches 4 workers and a queue each core runs one task, then takes the next only the 4 running tasks hold memory same work, done in order; the rest waits as a list
Both sides do the same work on the same 4 cores. The left side starts all 300 tasks at once, so they all run slowly and all hold their data. The right side runs 4 at a time.
core switch, switch

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.

limit

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

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.

main thread push(job) queue f e d front back ← new jobs · front → next to run worker 1a worker 2b worker 3c The queue is the only thing the main thread and the workers share, so only it needs a lock.
Three workers, six jobs. The first worker that finishes takes d.

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
Workers that wait on the disk

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.

One job worker 1 read model img 1 img 2 img 3 img 4 img 5 img 6 worker 2idle workers 3, 4idle done A child job per image worker 1 read model img 1 img 5 worker 2 img 2 img 6 worker 3 img 3 worker 4 img 4 done: the last child finishes the model The read pushes 6 children. Four start at once; the two left run on the first workers that are free.
The same work in less than half the time on 4 workers. A child job has the same rules as any job: its data in, its result out.

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

the only worker parent: wait() queue waits for the children; they wait for a worker deadlock

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

parent: n = 3 n → 2 n → 1 n → 0 finish the model The parent ends at once. Nobody waits. one worker runs them all, one by one

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

worker parent: read, n = 3, push A B C queue A B C counter n3 The parent job ends here. The worker is free.

The parent does not wait. It only leaves a counter and three jobs.

2. Children run and count down

worker parent A: n 3 → 2 B: n 2 → 1 queue C counter n1 A and B are not the last: they write their own result and end.

Each child writes only its own result, then counts down. The order does not matter.

3. The last child finishes the task

worker parent A B C: n 1 → 0 finish, hand over counter n0 One worker ran everything, and no job ever waited.

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:

n → 0 the last one runs the next step

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

wait: help runs queued jobs while it waits

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

stack next job a paused job keeps its stack

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.

Turn the budget off and look at the memory curve. Then turn it on and lower it: find a budget that keeps the memory low while all 24 images are in almost as soon. Then set one worker.
budget

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.

slow: workers idle

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

3 2 1 first in, first out

FIFO

Jobs run in the order they were asked for. Simple and fair: nothing waits forever.

children new tasks 1st2nd

Children first

A started task finishes before new ones start, so its memory goes soon, and its result arrives early.

123 near first

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

core 1 main worker's job main core 2 idle the frame waits 2 to 4 ms in notify_all

Worker one level below

core 1 main goes on core 2 worker's job a free core runs it at full speed

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.

RUNNING queued or running job: result written main thread: cancel DONE the main thread uses or frees it DROPPED the job frees it when it ends Both arrows are a compare-and-exchange from RUNNING: if the other side got there first, it fails, and this side frees the result.
Exactly one side frees the result, also when the cancel and the end happen at the same moment.
skipped, never run

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.

flag set checks between steps

Running

A job cannot be stopped from outside. It checks the flag between its steps and skips the rest, then ends as usual.

result the main thread frees it

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:

  1. cancelSet every ticket's flag, so running jobs skip their next steps.
  2. stopSet the pool's stop flag and empty the queue; jobs pushed now are dropped.
  3. wakeWake every sleeping worker, so it sees the stop flag.
  4. joinWait for each thread to end. Only then free what the jobs use.
A job must not hold the engine

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

A B C B, A, C … or A, C, B

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

A B C slot A slot B slot C

The slots are made before the jobs start, so no job changes the list itself. The finish step reads them in a fixed order.

What may still differ

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).

main thread loadMesh(path) ticket, estimate: file size WorkerPool children queue (taken first) loads queue: starts if bytes fit runMeshImport parse; images: a gated next step runImageWorkimage 1 runImageWorkimage 2 … buildMeshLodsper sub-mesh each: n − 1 the one that makes n = 0 completeMeshLoad finishImageWork, ticket DONE finishLoads upload; a worker frees it destroyMesh drops the ticket: a queued load never runs; a running one skips its next steps. loadTexture and loadEnvironment are one load job each, with no children.
No job waits for another, so the pool works with one thread. A worker thread is named RASM loader N in Tracy.

Where RASM follows the page, and where it differs

PartThis pageRASM
Workershardware threads minus the busy onesEngineConfig::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.
Priorityworkers below the main threadEach 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).
QueueFIFO, children first, priorityTwo 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.
Splita child job per partspawnMeshChildJobs 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.
Waitingcontinuation, help, fibersContinuation: 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.
Budgeta job starts if its bytes fit, or nothing is heldEngineConfig::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.
Cancelticket: flag and stateLoadTicket: 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.
Shutdowncancel, stop, wake, join~AssetLoader drops every pending load, then WorkerPool::shutdown empties the queues and joins the threads, before anything else is destroyed.
Same resulteach job its own slotThe 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.

535 → 110 msFlight Helmet KTX2, whole load15 images transcoded on several workers
931 → 191 msFlight Helmet PNGdecode and mips of each image in its own job
1052 → 200 msSponza69 JPEG and PNG images
3519 → 2964 MiB300 images asked in one framepeak private memory; at most 512 MiB decoded at once

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

WhatWhere
The pool, ticketsWorkerPool, WorkerJob, LoadTicket in src/core/workerPool.h, src/core/workerPool.cpp
A load's shared dataMeshLoadJob, TextureLoadJob, EnvironmentLoadJob in src/assets/loadJobs.h
Mesh load jobsrunMeshImport, endMeshChildJob, completeMeshLoad, AssetLoader::Impl::loadMesh in src/assets/meshLoad.cpp
Image jobsparseMeshFile, runImageWork, finishImageWork, GltfImageWork in src/assets/meshImport.cpp
Texture and environment jobsAssetLoader::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, shutdownfinishLoads, finishReadyLoads, getLoadStats, dropAll (from ~AssetLoader) in src/assets/assetLoader.cpp
Settings and statsAssetLoaderConfig::loadThreads, loadMemoryBudget (also in EngineConfig), LoadStats in include/rasm/types.h; the RASM window's Loads line
Teststests/workerPoolTests.cpp: order, children first, one worker with nested children, cancel, budget, shutdown
Examples, numbersexamples/17_streaming (--burst), examples/10_ktx2_textures (--measure), tools/load_bench.py
APIgetLoadStats, LoadStats, EngineConfig
Keep these true
  • 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_ptr and 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 DONE goes back from the worker that frees it; the job gives back what it held when it ends DROPPED.
  • 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.
Not done yet

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