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.
- std::async
- Starts a function, with std::launch::async on a new thread, and returns a std::future for its result.
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.
| Work | Concurrent on one core | Parallel on several cores |
|---|---|---|
| Independent waits (timer model) | Pending durations can overlap | Additional CPU may help processing overhead, not shorten the declared waits |
| Fixed CPU work | No extra execution capacity from task structure alone | May 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.
#include <chrono>
#include <cstdio>
#include <functional>
#include <thread>
#include <vector>
using Clock = std::chrono::steady_clock;
/// Busy work: a fixed number of loop iterations.
unsigned long compute(unsigned long iterations) {
volatile unsigned long x = 0;
for (unsigned long i = 0; i < iterations; ++i) x = (x * 31 + i) % 1'000'003;
return x;
}
/// Iterations that take about `ms` milliseconds on one thread.
unsigned long calibrate(long ms) {
unsigned long iterations = 1'000'000;
for (;;) {
const auto start = Clock::now();
compute(iterations);
const long took = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start).count();
if (took > 50) return iterations * ms / took;
iterations *= 2;
}
}
/// Runs `task` on three threads at once and reports the elapsed time.
void timed(const char* label, const std::function<void()>& task) {
const auto start = Clock::now();
std::vector<std::jthread> threads;
for (int i = 0; i < 3; ++i) threads.emplace_back(task);
threads.clear();
const long ms = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start).count();
std::printf("%s: about %ld ms\n", label, (ms + 50) / 100 * 100);
}
int main() {
const unsigned long work = calibrate(300);
std::printf("cores reported: %u\n", std::thread::hardware_concurrency());
timed("3 waiting tasks", [] { std::this_thread::sleep_for(std::chrono::milliseconds(300)); });
timed("3 computing tasks", [work] { compute(work); });
}
g++ -std=c++23 -Wall -Wextra -pedantic main.cpp -o main && ./main
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.
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.
Check this idea later
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.
"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.
Sign in to keep your read marks on every device. Sign in
Was this helpful?