← Runtimes
Runtimes

Threads, tasks, and goroutines

Know who schedules each unit of work, and when you have to wait for it.

Relate a unit of work to its scheduler, its resource cost, and the boundary that establishes completion.

Outcome

Compare runtime tasks with operating-system threads, predict how many threads a program uses, and make code wait for all the work it starts, including work started by that work.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Operating-system thread
A unit of execution the kernel schedules onto cores. Each needs execution state and a stack; stack reservation and limits depend on the platform and configuration.
Runtime task
A unit of work scheduled in user space by a runtime or executor onto operating-system threads. The runtime determines the mapping.
Async task
Here, an async function invocation whose promise represents completion. Its initial synchronous code runs at the call; later continuations run on the same Node JavaScript agent.
Join
Wait for a thread or task to finish.
Structured concurrency
Giving child work a lifetime bounded by its owning scope. Rust thread::scope joins its scoped threads; promise aggregation needs separate failure and cancellation policies.

Work units and their execution resources

An operating-system thread supplies execution state that the kernel can schedule. A runtime task represents work that a language runtime or executor arranges to run on threads. The distinction matters when many activities spend most of their lifetime waiting: the number of activities need not equal the number of threads.

Launching an activity and observing its completion are separate responsibilities. A join or completion handle lets an owner wait for a defined piece of work. If that work launches children, decide whether its completion also covers those children; a scheduler does not decide that API promise for the caller.

01Who schedules?

The kernel schedules threads; runtimes schedule tasks

The site checker reports its starting pages as checked, but the linked pages are still running. Before expanding the crawl, its maintainer needs to know what each launch creates and what a completed visit promises. A Linux thread-count probe helps separate the resource question from the missing waits.

The kernel schedules operating-system threads. Go adds a scheduler that multiplexes goroutines across them. In this Node program, JavaScript executes on one agent; timer waits let other ready continuations run. Node can also use worker threads and native workers, which this probe does not create. Rust and C++ use standard threads here. Rust futures and C++ coroutines provide other building blocks, but an executor must drive that work.

The unit used by these probes
LanguageUnit you startScheduled by
TypeScriptasync function / PromiseNode’s event loop, on one JavaScript thread
Gogoroutine (go f())Go runtime; GOMAXPROCS bounds simultaneous Go execution, not total OS threads
Ruststd::thread::spawn / thread::scopeThe kernel (tasks need a runtime crate such as Tokio)
C++std::thread / std::jthreadThe kernel (C++20 coroutines need a library executor)

02Count the threads

What a waiting unit of work costs

This program reads Linux’s /proc/self/status, starts waits of 300 ms, then samples the thread count after a 100 ms delay. TypeScript and Go launch 1,000 waits; Rust and C++ launch 50 threads. The delay is a sampling opportunity, not a barrier proving every worker is still waiting.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { readFileSync } from 'node:fs';

/** Operating-system threads in this process, from Linux's /proc/self/status. */
function osThreads(): number {
  return Number(/Threads:\s+(\d+)/.exec(readFileSync('/proc/self/status', 'utf8'))![1]);
}

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

async function main(): Promise<void> {
  console.log(`before: ${osThreads()} OS threads`);
  const tasks = Array.from({ length: 1000 }, () => sleep(300));
  await sleep(100);
  console.log(`while 1000 async tasks wait: ${osThreads()} OS threads`);
  await Promise.all(tasks);
}

void main();
terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc --noEmit --strict main.ts && node main.ts
In the recorded Linux run below, what thread count was observed after starting 1,000 async tasks?

03Waiting for work

Starting work is not finishing it

Launching work and completing it are separate events. A new thread can run before the launch call returns, and an async function runs synchronously until it suspends. The checker needs a stronger guarantee than an early return: its completion promise, WaitGroup or joined handles must cover the writes to the visited list.

In this authored timeline, work starts at t = 0 and records its result at t = 100 ms. The report reads the count at t = 1 ms without waiting. What does it print?

04Practice

Check every page

In Node’s single JavaScript agent, a check and claim with no await between them runs without another promise continuation interleaving. Go, Rust and C++ workers need synchronized shared claims: the check and insertion form one critical section. Release its lock before the page wait or any child join. A claim establishes ownership of work, not its completion.

The lab models a page fetch with a native timer or sleep and a recorded page name; it makes no HTTP request. The report snapshots the list when crawl returns. A missing name exposes incomplete work; a name that happens to be present does not prove it was joined. Node’s referenced timers can keep its process alive after that report, while returning from Go or Rust main ends the process. The supplied C++ driver flushes its snapshot and exits without static destruction so an incorrect detached worker cannot race global teardown.

The site checker

Make a fetch finish its own work, extend a check to direct links, then follow shared and cyclic links without duplicate work or unfinished descendants.

  1. easy · R-TASK-V4-1 Wait for the fetches
  2. medium · R-TASK-V4-2 Wait for real
  3. hard · R-TASK-V4-3 Wait for work started later
Check this idea later
A chat server is choosing a design for 50,000 mostly idle connections, subject to normal memory and process limits. Which is the more practical starting point?
save returns promises that settle after a later event-loop turn. With nonempty items, items.forEach(async (item) => await save(item)); console.log("saved"). When is saved printed?
A job runner waits for each job it starts. Jobs start background subtasks and return. When the runner reports done, are the subtasks done?
Sources
In the frontend A callback return type is part of the completion boundary. Optional

A check button accepts onCheck from its parent. The parent passes an async function that finishes on a later event-loop turn. Review this incomplete handler: what does the Checked label establish about the parent’s operation?

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
'use client';

import { useState } from 'react';

export default function CheckButton({ onCheck }: { onCheck: () => void }) {
  const [status, setStatus] = useState('Ready');

  function handleClick() {
    onCheck();
    setStatus('Checked');
  }

  return <button onClick={handleClick}>{status}</button>;
}

The callback’s void contract gives this caller no completion promise to wait on. TypeScript allows an async function where a void-returning callback is expected; this handler discards that promise.

The label update is scheduled after invoking onCheck, before the specified pending operation settles. React decides when to render; this source does not establish a browser paint time. Decide what completion the component’s API should promise before repairing the handler.

Sources: React: responding to events,Svelte: event handlers,TypeScript: void-returning function assignability.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.