← Runtimes
Runtimes

Concurrency and parallelism

Tell overlapping work from simultaneous work.

Separate overlapping task lifetimes from the execution capacity available to do their work.

Outcome

Distinguish concurrent structure from parallel execution, predict when overlapping tasks finish sooner, and schedule work within a fixed number of execution slots.

Terminology (6)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.

Concurrency
Structuring a program as tasks whose lifetimes overlap. It says nothing about whether any two run at the same instant.
Parallelism
Executing task work simultaneously using available hardware execution capacity. Logical processors, physical cores and CPU-time budgets are different quantities.
Scheduler
The part of the operating system or runtime that decides which ready task runs next, and where.
CPU-bound
Work dominated by CPU execution. Launching more tasks alone does not reduce its work; algorithms, optimization and available capacity also matter.
I/O-bound
Work whose time is spent waiting for something outside the CPU, such as a network reply or a disk.
Event loop
The event-processing loop of this Node JavaScript agent, which runs one callback at a time. Native asynchronous work or other workers have separate execution.

Tasks, waits, and execution capacity

A task is an activity with a start, some work, and a completion. During its lifetime it can be ready to run, executing, or waiting for an external event. Waiting for a timer or response differs from consuming CPU time: a pending wait can leave execution capacity available for another task.

CPU-bound work spends most of its time computing; I/O-bound work spends much of it waiting for outside progress. Identify which resource limits the workload before estimating a speedup. A scheduler chooses which ready work uses the available resources, while the program determines which activities may overlap.

01Two different ideas

Overlapping is not the same as simultaneous

The report builder waits for independent source files, then performs a CPU-heavy formatting stage. Starting the waits together can remove avoidable idle time; wrapping the formatter in async functions does not create execution capacity. After imposing the file service’s connection cap, a long year export exposes another idle gap: the code waits for its whole pair before using a newly free slot.

Concurrency describes overlapping task lifetimes. Parallelism describes simultaneous execution. One execution slot can interleave ready tasks while pending waits release that slot. A physical core may expose several logical processors, and a CPU-time quota is an aggregate budget rather than a fixed number of simultaneously running threads.

What each kind of work needs to finish sooner
WorkConcurrent on one coreParallel on several cores
Independent waits (timer model)Pending durations can overlapAdditional CPU may help processing overhead, not shorten the declared waits
Fixed CPU workNo extra execution capacity from task structure aloneMay reduce elapsed time, subject to work division and overhead

02Waiting versus computing

Three tasks that wait, three tasks that compute

This program first measures how much loop work takes about 300 ms on one thread. Then it runs three tasks that each wait 300 ms, the way a download waits on a remote service, and three tasks that each do that 300 ms of work, the way an image conversion computes. The program requests overlap and reports elapsed time. The current TypeScript probe uses three explicit timer handles to expose initiation before waiting, then calls compute three times synchronously. Its wrapper’s async keyword does not yield during those loops. The table’s TypeScript row is an earlier Promise.all variant of the same workload shape; the current spelling has not been timed. The other variants launch runtime/OS threads. The historical runner had an aggregate one-CPU-time quota; that does not rule out brief simultaneous execution before throttling.

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

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

/** Busy work: a fixed number of loop iterations. */
function compute(iterations: number): number {
  let x = 0;
  for (let i = 0; i < iterations; i++) x = (x * 31 + i) % 1_000_003;
  return x;
}

/** Iterations that take about `ms` milliseconds on one thread. */
function calibrate(ms: number): number {
  let iterations = 1_000_000;
  for (;;) {
    const start = performance.now();
    compute(iterations);
    const took = performance.now() - start;
    if (took > 50) return Math.round((iterations * ms) / took);
    iterations *= 2;
  }
}

async function timed(label: string, run: () => Promise<unknown>): Promise<void> {
  const start = performance.now();
  await run();
  console.log(`${label}: about ${Math.round((performance.now() - start) / 100) * 100} ms`);
}

async function main(): Promise<void> {
  const work = calibrate(300);
  console.log(`cores reported: ${availableParallelism()}`);
  await timed('3 waiting tasks', async () => {
    const first = sleep(300);
    const second = sleep(300);
    const third = sleep(300);
    await first;
    await second;
    await third;
  });
  await timed('3 computing tasks', async () => {
    compute(work);
    compute(work);
    compute(work);
  });
}

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
For an ideal work-budget estimate, each task requires 300 CPU-ms, unchanged between runs. Assume one CPU of capacity delivered steadily, with no overhead, quota-period bursts or optimization changes. About how long does all three tasks’ work take?

03Scheduling within limits

A limit on resources needs a scheduler

The file service’s connection cap limits in-flight operations. Use a separate model for a rate quota or CPU-time budget. For this scheduling question, jobs are independent, durations are fixed, slots are identical and dispatch has negligible overhead; assign ready jobs in queue order to model the builder’s makespan.

The report builder needs seven files from a file service that allows it two connections. In queue order, the first file is a full-year export that takes 6 seconds to download; the other six are monthly exports that take 1 second each. The builder starts downloads in pairs and waits for both of a pair to finish before starting the next pair. How long until every file is downloaded?

04Practice

Download within a deadline

The lab performs real timer/thread sleeps to stand in for downloads; it makes no HTTP, network or file-service requests. Supplied code measures the elapsed time against a deadline and counts how many downloads were in flight at once. The authored cases leave timing margins, including 150 ms for Hard’s long-job profile. A sufficiently delayed runner can still miss a deadline with correct source; the counters are supplied instrumentation, not an adversarial enforcement boundary.

The report downloader

Simulated downloads use real timer/thread sleeps, with a deadline and an in-flight counter. Make them overlap, respect a limit on how many run at once, then keep every slot busy when durations differ.

  1. easy · R-CONC-V4-1 Overlap the waits
  2. medium · R-CONC-V4-2 Respect the limit
  3. hard · R-CONC-V4-3 Keep both slots busy
Check this idea later
A Node service resizes 10 images with an async function each, started together with Promise.all. Resizing is pure JavaScript computation. Compared with resizing one after another, it finishes…
A container has a 2-CPU aggregate time quota on an otherwise idle 64-logical-CPU host. A Go program explicitly sets GOMAXPROCS(64) after runtime.NumCPU() returns 64 and keeps 64 CPU-bound goroutines runnable. Over many quota periods, which describes its sustained budget rather than a brief parallel burst?
A job runner may use 4 connections. Independent fixed-duration jobs vary from 1 to 30 seconds. Which approach usually finishes sooner?
Sources
In the frontend An async button can still block Optional

This client-side button receives a synchronous report builder. The async handler calls it on the same JavaScript agent; setting a status first does not create a worker or guarantee an intermediate paint. Use this boundary to decide whether the task is waiting on something or consuming the UI thread.

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

import { useState } from "react";

export default function ReportButton({ build }: { build: () => string }) {
  const [status, setStatus] = useState("Ready");

  async function run() {
    setStatus("Building");
    const report = build();
    setStatus(report);
  }

  return (
    <>
      <button onClick={run}>Build report</button>
      <output>{status}</output>
    </>
  );
}

build is a local synchronous callback supplied by client code. React state batching and browser painting are separate from task launch. This example supplies no worker protocol and makes no frame-rate claim.

Sources: Node.js: blocking synchronous JavaScript work,React: queued state updates,Svelte: state and update timing.

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.