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.
| Language | Unit you start | Scheduled by |
|---|---|---|
| TypeScript | async function / Promise | Node’s event loop, on one JavaScript thread |
| Go | goroutine (go f()) | Go runtime; GOMAXPROCS bounds simultaneous Go execution, not total OS threads |
| Rust | std::thread::spawn / thread::scope | The kernel (tasks need a runtime crate such as Tokio) |
| C++ | std::thread / std::jthread | The 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.
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();
npx tsc --noEmit --strict main.ts && node main.ts
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.
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.
Check this idea later
Sources
- Go: the Go scheduler (runtime/proc.go)
- ECMAScript: Promise.all
- Go: sync.WaitGroup
- Node.js: the event loop
- Rust: std::thread::scope
- C++ standard draft: thread destruction
- C++ standard draft: process termination
- Node.js: process and event-loop lifetime
- Go: GOMAXPROCS
- Linux man page: proc_pid_status(5), Threads
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?
'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.
Sign in to keep your read marks on every device. Sign in
Was this helpful?