skip to content

In an engine's job system, why does a job that must wait on other jobs mid-run push teams toward fibers, and what do fibers cost?

level: seniorimportance: should knowfreq 40%

answer

  1. a job that waits mid-run
  2. workers asleep, children queued
  3. park the stack, run something else
  4. resume on any worker thread

basics

~20 s

A job that waits on other jobs blocks its worker, idling a core or deadlocking the pool. Fibers park the waiting job's stack so the worker runs other jobs and any worker resumes it later, costing a stack per fiber and thread-local pitfalls.

solid answer

~50 s

In a thread-based job system a job that must wait for jobs it spawned has three poor options: **block** its worker, which idles a core and deadlocks the pool if every worker waits on children still queued; **help while waiting** by running other jobs on top of its own stack, which buries it so it cannot resume until those return; or be **rewritten as continuations**, splitting the code at every wait. A **fiber** is a user-mode execution context with its own stack. When a job waits, the worker parks the fiber on a wait list tied to the counter, switches to a fresh fiber and keeps taking jobs; when the counter reaches its target, any worker resumes the parked fiber. The costs: a stack per fiber, thread-local data that differs when a fiber resumes on another worker, OS locks that must not be held across a wait, and harder debugging.

code

pseudocode · 12 lines
pseudocode
// counters count down; the wait is over once the counter reaches target
function wait_for_counter(counter, target):
    if atomic_load(counter) <= target:
        return                                  // nothing to wait for
    me = current_fiber()
    next = fiber_pool.take_free()
    // park 'me' only after the switch has saved its registers, so no
    // other worker can resume a fiber that is still running here
    switch_to(next, after_switch = function():
        if not wait_list.register_if_pending(counter, target, me):
            ready_fibers.push(me))              // counter finished meanwhile
    // execution continues here when resumed, possibly on another worker

go deeper

for a junior

Recall that a fiber is a lightweight execution context with its own stack, switched by the program itself instead of by the operating system.

for a middle

Explain why a job that blocks while waiting wastes a worker, and how a fixed pool deadlocks when every worker waits on children still in the queue.

for a senior

Compare blocking, help-while-waiting, continuations and fibers, and name the fiber hazards: per-fiber stack memory, thread-local data after resuming elsewhere, and locks held across a wait.

for a principal

Weigh fibers against a continuation style for a whole engine: tools and third-party code that assume threads, against how easily gameplay programmers can write jobs that simply wait.

## The problem: a job that waits Many jobs are naturally written as "spawn some children, wait for them, carry on": a job that kicks off a parallel-for over its objects and then needs the results. In a job system whose jobs run directly on worker threads, that wait has three classic answers, and each hurts. - **Block the worker.** The worker sleeps until the counter reaches zero. It frees its core, but the pool has nothing to put on it, so the core idles. Worse, if all eight workers each run a parent that waits on children still sitting in the queue, nobody is left to run the children and the frame **deadlocks**. - **Help while waiting.** The waiting worker runs other ready jobs until its counter reaches zero. Those jobs run on top of the waiting job's stack, so even after its counter hits zero the waiting job cannot resume until the borrowed job returns. A critical-path job can sit buried under unrelated work, and nested waits grow the stack. - **Continuations.** Forbid waiting: the code after the wait becomes a separate job that depends on the children. It works, but every function with a wait is split in two and its local state must be carried by hand. ## What a fiber is A **fiber** is a user-mode execution context: its own stack plus a saved set of registers. A thread can switch from one fiber to another by saving its current registers and stack pointer and loading the other fiber's, entirely in user mode, with no call into the kernel scheduler. Switching is far cheaper than switching OS threads, and it is **cooperative**: a fiber runs until it chooses to switch. ## A fiber-based job system 1. Start a fixed set of worker threads, often one per core, and a pool of fibers with preallocated stacks. 2. A worker takes a ready job and runs it on a free fiber. 3. When the job waits on a counter that has not reached its target, the worker records the fiber on a **wait list** for that counter and switches to a fresh fiber, which takes the next ready job. 4. When the counter reaches its target, the job that finished last moves the parked fiber to the ready list. 5. Any worker, not necessarily the original one, picks the fiber up and resumes it exactly after its wait. Jobs can now wait freely in the middle of a function, and workers need not sleep while ready work exists. ## Costs and hazards - **Stack memory.** Every fiber needs its own stack. In an illustrative pool of 160 fibers with 64 KB stacks, that reserves 160 x 64 KB = 10,240 KB, about 10 MB. Small stacks also need overflow detection, such as guard pages. - **Thread-local data.** A fiber may resume on a different worker than the one it started on, so a thread-local value read before the wait belongs to the old thread. Some compilers even cache a thread-local address across the switch unless told the code is fiber-safe. - **Locks.** A fiber that holds an OS mutex and then waits is parked while holding it, blocking every worker that needs it, possibly the very workers that would finish its counter. Many OS mutexes must also be released by the thread that acquired them. Fiber-aware locks that switch fibers instead of blocking the thread avoid both problems. - **Tooling.** Debuggers and profilers built around threads may not show parked fibers' stacks, which makes hangs harder to read. ## Choosing an approach | Approach | What the waiting job does | Main cost | |---|---|---| | Block the worker | Sleeps on its thread | Idle core; deadlock when every worker waits on queued children | | Help while waiting | Runs other jobs on its own stack | Cannot resume until borrowed jobs return; stack depth grows | | Continuations | Never waits; the rest becomes a new job | Code split at every wait; state carried by hand | | Fibers | Parks on a wait list | Stack per fiber; thread-local and lock hazards | Engines that build the frame's graph up front can live with continuations alone; engines whose gameplay code wants to wait mid-function are the ones that adopt fibers.

  • Why are ordinary OS locks a hazard in a fiber-based job system?
    A fiber that holds a mutex and then waits on a counter is parked still holding it, so every worker that needs the lock blocks, possibly the workers that would finish that counter. Many OS mutexes must also be released by the acquiring thread, which a resumed fiber may no longer be on. Fiber-aware locks that switch fibers instead of blocking avoid both.
  • How can an engine avoid fibers and still never block a worker?
    Build the frame's job graph up front so no job waits mid-run: the work that would follow a wait becomes a separate job that depends on the jobs it would have waited for. That continuation style needs no fiber stacks, at the price of splitting functions at every point where they would have waited.

  • A blocked worker is harmless because the OS simply runs queued jobs on that core.
  • Switching fibers costs the same kernel context switch as switching OS threads.
  • Fibers are preemptive, so a long job is interrupted automatically to run waiting work.
  • Thread-local data stays valid across a fiber wait because the fiber keeps its own stack.
  • Fibers remove the need to express dependencies between jobs.