Exploiting concurrency
The sort decision fanned out across the diverter lanes three ways: sequential, data-parallel (fixed slices across std::jthread), and task-parallel (one task per parcel through a thread pool), measured for throughput against the scan-to-divert deadline, plus the identical data-parallel split in Rust, where the disjoint output split is a compiler-checked borrow instead of a convention.
Learning objectives
By the end of this chapter you can:
- Name the two ways to split independent work across threads, data-parallel (one operation over disjoint slices of a batch) and task-parallel (independent units scheduled dynamically across a pool), and say which one this chapter’s workload favors and why.
- Build a small, reusable thread pool on
std::jthreadandstd::stop_token, usingstd::future/std::packaged_taskto collect task results. - Read a batch’s completion-time distribution against a fixed deadline and say which scheduling strategy actually holds that deadline and which only looks fast on average.
- Explain why splitting a batch’s output across threads needs no lock in
either language, and what Rust’s
std::thread::scopepluschunks_mutadds that C++’s hand-computed[begin, end)ranges leave to a reviewer: a disjoint split as a type the compiler checks, not a loop bound someone verifies by hand. - State why more threads did not buy proportionally more throughput here, and name the two real reasons (shared hardware threads, a shared clock budget) rather than treating the sublinear scaling as a bug.
Diagram
Why this matters
“Wait-free synchronization” fixed how two threads hand off one decision. This chapter asks a different question: once a batch of parcels needs the same decision made many times over, how more than two threads turn that into throughput without missing the deadline any one parcel is still held to.
The scan stage resolves each parcel’s destination chute independently of every other parcel, the same workload shape this book has used since “Eliminating work,” except this time the per-parcel cost is real: a brute-force nearest-chute search over a few hundred candidates, cheap for one parcel and expensive for a few hundred thousand of them arriving in a burst. One thread, run flat out, cannot clear that burst inside the scan-to-divert deadline this book set in “The latency budget.” The question is not whether more threads help, more compute almost always benefits from more cores, but how to split the work, and what each way of splitting it costs.
The sequential baseline
ch06::classify(parcel, chutes) is the workload: given a parcel’s
12-dimensional destination vector and a table of 256 chutes, it finds the
nearest chute by squared Euclidean distance, 256 candidates times 12
dimensions of multiply-add per call. It is pure, it reads its arguments and
writes nothing, so nothing about calling it concurrently needs a lock. The
sequential lane, run_sequential_trial, classifies a batch of 300,000
parcels on one thread, one at a time, and is both the correctness
reference every other lane is checked against and the baseline every
other lane’s throughput is measured against.
Splitting the work: data-parallel and task-parallel
There are two ways to turn one batch into parallel work. Data-parallel
decides the split before any thread starts: divide the batch into
worker_count contiguous slices and hand each slice to its own thread,
which runs the identical operation over nothing but that slice.
run_data_parallel_trial does exactly this with std::jthread:
const std::size_t chunk = (n + worker_count - 1) / worker_count;
std::vector<std::jthread> workers;
for (std::size_t w = 0; w < worker_count; ++w) {
const std::size_t begin = w * chunk;
const std::size_t end = std::min(n, begin + chunk);
if (begin >= end) { continue; }
workers.emplace_back([&, begin, end] {
for (std::size_t i = begin; i < end; ++i) {
result.resolved_chutes[i] = classify(parcels[i], chutes);
result.completion_us[i] = micros_since(start);
}
});
}
Nothing here needs a lock or an atomic. Every worker’s [begin, end) range
is fixed up front and never overlaps another worker’s range, so two
workers never write the same index of result.resolved_chutes or
result.completion_us. The std::vector<std::jthread> going out of scope
joins every worker before the function returns; std::jthread’s
destructor is the whole shutdown path.
Task-parallel decides the split dynamically instead: break the batch into
independent units of work (here, one parcel each) and let a pool of
worker threads pull them off a shared queue as they finish the last one.
ch06::ThreadPool is a small, reusable pool: a fixed number of
std::jthread workers, a std::queue<std::function<void()>> behind a
mutex, and a submit() that wraps the caller’s closure in a
std::packaged_task and hands back a std::future for its result, the
same return shape std::async offers for one call, reusable here across
many small ones without a new OS thread per call:
template <typename F>
auto submit(F&& task) -> std::future<std::invoke_result_t<F>> {
auto packaged = std::make_shared<std::packaged_task<...>>(std::forward<F>(task));
std::future<...> result = packaged->get_future();
{ const std::scoped_lock lock(mutex_); queue_.emplace([packaged] { (*packaged)(); }); }
not_empty_.notify_one();
return result;
}
run_task_parallel_trial submits one task per parcel, collects 300,000
futures, and waits on each in turn. Each task still only ever writes its
own output index, so this is exactly as race-free as the data-parallel
split; what differs is who decides which thread runs which parcel. The
pool decides at run time, the right shape when the units of work are not
equal size or not known in advance, a pipeline of stages, say, or requests
arriving at an unpredictable rate. It costs a lock, a queue push and pop,
and a heap-allocated packaged_task once per parcel, overhead the
data-parallel split’s fixed slices never pay.
Both are threads under the hood: std::jthread and the pool’s workers are
OS threads either way, so this chapter measures work granularity, not a
different concurrency primitive. Fibers and coroutines
(cooperative, user-scheduled units cheaper than an OS thread), an
event-driven single-threaded reactor, and an actor model (independent
units of state, communicating only by message) are the other shapes this
book names without building here; “Asynchronous processing” takes the
event-loop shape further, where cheap concurrency, not more CPU
throughput, is the point. classify() has no state of its own to
protect, each call is a pure function of its one parcel. The only shared,
mutable state in this entire example is the thread pool’s task queue,
guarded by one mutex: that is the full extent of this chapter’s
concurrency control. A workload with a real cross-parcel invariant, a
running total two chutes both update, say, does not get easier by adding
threads; it gets a lock, scoped as narrowly as this chapter’s queue, and
nothing wider.
The measurement
examples/06-exploiting-concurrency/cpp/ runs the identical 300,000-parcel
batch through all three lanes, every parcel’s resolved chute checked
against the sequential lane’s answer (*_mismatch_count reads 0 for
every lane, every run), and every parcel’s completion time checked against
a fixed 750,000-microsecond scan-to-divert deadline, the same deadline
this book set in “The latency budget” from a 2.0 m/s belt and a 1.5 m
scan-to-diverter distance. From results/exploiting-concurrency.txt,
measured on a 16-core/22-thread laptop CPU, powersave governor, bare
metal, no pinning or isolation:
| Lane | throughput | met the deadline | p50 | p99 | p99.9 |
|---|---|---|---|---|---|
| sequential (one thread) | 50,741 items/s | 37,995 / 300,000 | 2949782.395 us | 5854256.268 us | 5906740.575 us |
data-parallel (22 jthread slices) |
508,915 items/s | 300,000 / 300,000 | 271951.485 us | 567322.642 us | 585523.915 us |
| task-parallel (22-thread pool) | 202,526 items/s | 155,645 / 300,000 | 722543.947 us | 1432255.078 us | 1445327.308 us |
Data-parallel runs about 10.0 times the sequential lane’s throughput and clears the deadline for every single parcel in the batch. Task-parallel runs about 4.0 times the sequential lane’s throughput, better than one thread by a wide margin, but its own p50 (722543.947 us) already sits close to the 750,000-microsecond deadline, and it misses that deadline for about 48 percent of the batch. The sequential lane misses it for 87 percent of the batch: one thread, however correct, cannot keep up with a burst this size. The effect moves at every percentile together, because the deadline here is a property of the whole batch’s clear time, not one parcel’s queueing delay: splitting the batch is what shrinks that clear time, and how the split is decided, fixed up front or pulled dynamically, decides how much of that shrink survives 300,000 lock/unlock cycles on a shared queue.
The C++/Rust side-by-side
The data-parallel split is the same idea in both languages: divide the batch into fixed slices, run one thread per slice, write only that slice’s output.
workers.emplace_back([&, begin, end] {
for (std::size_t i = begin; i < end; ++i) {
result.resolved_chutes[i] = classify(parcels[i], chutes);
result.completion_us[i] = micros_since(start);
}
});
for ((parcel_slice, resolved_slice), completion_slice) in
parcel_chunks.zip(resolved_chunks).zip(completion_chunks)
{
scope.spawn(move || {
for ((parcel, out), done) in parcel_slice
.iter()
.zip(resolved_slice.iter_mut())
.zip(completion_slice.iter_mut())
{
*out = classify(parcel, chutes);
*done = start.elapsed().as_secs_f64() * 1e6;
}
});
}
resolved_slice and completion_slice come from resolved.chunks_mut(chunk)
and completion_us.chunks_mut(chunk): slice::chunks_mut is the only way
to obtain more than one &mut sub-slice of the same Vec, and it returns
slices the borrow checker already knows are disjoint. The split itself is
language-neutral; what is not neutral is who checks that it stays that
way. The C++ lane computes begin and end by hand, and an off-by-one
that overlaps two workers’ ranges by a single index still compiles, links,
and runs, racing on that index under a timing-dependent schedule; TSan
would likely catch it on the run where the race fires, not as a standing
guarantee for every run after. Rust’s version makes the identical mistake
a compile error:
// Nothing in run_data_parallel_trial's loop stops this: an off-by-one in
// the begin/end arithmetic that overlaps two workers' ranges by one index
// compiles, links, and runs. Whether it corrupts resolved_chutes[i]
// depends on how the two writes happen to interleave.
// Splitting a batch across worker threads with disjoint, compiler-checked
// mutable slices (chunks_mut) is the only way std::thread::scope lets more
// than one thread share &mut access to the same Vec. Skip the split and
// hand the whole output slice to two threads instead, and it does not
// compile:
let mut resolved = vec![0i32; 8];
thread::scope(|scope| {
scope.spawn(|| { resolved[0] = 1; });
scope.spawn(|| { resolved[1] = 2; }); // error[E0499]: cannot borrow
// `resolved` as mutable more
// than once at a time
});
This is checked by a compile_fail doc test on every cargo test run (see
rust/src/lib.rs’s doc comment on run_data_parallel). Running the same
split through examples/06-exploiting-concurrency/rust/src/bin/fanout_bench.rs
over the same 300,000-parcel batch, the same technique in Rust, not a
comparison against the C++ numbers above: p50 = 12108.420 us, p99 =
24791.459 us, p99.9 = 25968.932 us, mismatch_count = 0, every parcel
inside the deadline. The Rust binary is built in release mode, the way
anyone measuring a Rust program would; the C++ numbers above come from
this book’s default, unoptimized Debug preset, so the two sets of absolute
numbers differ in magnitude for that reason alone, well before any
question of language speed, which is why this chapter never computes a
ratio between them. The reason to reach for the Rust lane here is the same
as “Wait-free synchronization”: cargo test turns a convention, two
workers’ output ranges never overlap, into a type the compiler checks
once, in std, rather than a loop bound a reviewer checks by hand.
How the code works
The workload. ch06::Parcel (parcel_id, a 12-float destination)
and ch06::ChuteTable (256 Chutes, each a 12-float center) live in
include/ch06/parcel.hpp; build_chute_table and generate_parcels build
both deterministically from a seed, so every lane classifies against the
identical table and batch.
The thread pool. ch06::ThreadPool (include/ch06/thread_pool.hpp,
src/thread_pool.cpp) is a fixed set of std::jthread workers reading
from one std::queue<std::function<void()>>. Each worker’s loop waits on
std::condition_variable_any with its own std::stop_token as the wake
predicate’s third argument, so the destructor’s request_stop() plus one
notify_all() is the entire shutdown path; std::jthread’s own destructor
joins every worker once its loop returns.
The three trials. run_sequential_trial, run_data_parallel_trial,
and run_task_parallel_trial (src/fanout_trial.cpp) share one shape: a
FanoutTrialResult holding resolved_chutes, a completion_us timestamp
per parcel (microseconds since the trial started, the value the chapter’s
distributions and deadline check are built from), and total_wall_time_us.
main.cpp runs all three, cross-checks the two parallel lanes’
resolved_chutes against the sequential lane’s, and writes
results/exploiting-concurrency.txt.
The Rust lane. ch06_exploiting_concurrency::run_data_parallel
(rust/src/lib.rs) builds the identical split with std::thread::scope
and chunks_mut; classify_all_sequential is its own correctness
reference. rust/src/bin/fanout_bench.rs runs the same 300,000-parcel
batch and reports the same shape of result.
Build, run, observe
cd examples/06-exploiting-concurrency && ./demo.sh
Look for fanout_data_parallel_met_slo_count reaching the full batch
count while fanout_sequential_met_slo_count and
fanout_task_parallel_met_slo_count both fall short of it,
fanout_data_parallel_throughput_items_per_sec several times the
sequential lane’s, and *_mismatch_count reading 0 for every lane: the
split clears the deadline without changing a single resolved chute.
Trade-offs
Splitting a batch across threads is not free, and this chapter’s numbers show where the cost lands. Task-parallel’s per-task mutex/condition_variable overhead, paid 300,000 times, is why it delivers roughly 4.0 times the sequential lane’s throughput while data-parallel delivers roughly 10.0 times: the same 22 worker threads, the same workload, but one pays a lock and a heap allocation per parcel and the other pays nothing beyond the work itself. Task-parallel earns that cost back the moment the units of work are unequal, unknown in advance, or arrive over time rather than as one batch; a fixed up-front split cannot adapt to any of those and would leave a worker idle while another worker’s slice still has the long items in it.
Neither lane gets 22 times the sequential throughput, and this chapter
names why rather than waving it away. This CPU reports 16 physical cores
and 22 logical threads; classify() is floating-point ALU-bound work, and
two logical threads sharing one physical core’s execution ports do not
each get a full core’s worth of it, so the real ceiling sits closer to 16
times than 22. The remaining gap, roughly 10.0 times measured against that
16-times ceiling, is a clock-speed story on an unpinned, un-isolated
laptop under the powersave governor (see “Never change the development
host” for why this book never isolates cores to chase a cleaner number):
the sequential lane ran on one busy core free to turn up its clock, and
the data-parallel lane kept all 22 logical threads busy at once, a load
the chip sustains at a lower clock than one core alone gets to run at.
Amdahl’s Law, from “The latency budget,” says the same thing in its own
terms: a workload this close to fully parallel still cannot outrun the
hardware it runs on.
What you learned
- Data-parallel decides the split before any thread starts; task-parallel decides it dynamically, at the cost of a shared queue every unit of work passes through.
- A fixed, non-overlapping slice needs no lock to stay correct in either
language; what differs is whether that non-overlap is a convention a
reviewer checks or a type (
chunks_mut’s disjoint&mutslices) the compiler checks. std::jthreadplusstd::stop_tokenturns a thread pool’s shutdown path into onerequest_stop()and onenotify_all(), but that is only safe because the pool declares itsstd::jthreadworkers last: declaration order is destruction order reversed, so the workers join first, while the queue, mutex, and condition variable they still touch are alive.- Splitting work across more threads does not buy a speedup equal to the thread count: shared hardware execution ports and a shared clock budget under sustained load both cap it below the naive expectation, on this host closer to 10 times than 22 times, and that gap is physical, not a flaw in either lane’s code.
- Threads, a thread pool, and futures are mechanism; data-parallel versus task-parallel is the actual design decision this chapter measures, and it depends on whether the units of work are equal-sized and known up front.
The next chapter keeps the same single box and asks what happens when the same answer gets asked for more than once: a cache in front of the routing table, and which eviction policy actually pays for itself.
For deeper coverage
- Pekka Enberg, Latency: Reduce Delay in Software Systems (Manning, 2025): this guide’s reference work for chapter arc and coverage; see the bibliography.
- Maurice Herlihy, Nir Shavit, Victor Luchangco, and Michael Spear, The Art of Multiprocessor Programming, 2nd ed. (Morgan Kaufmann): the formal treatment of data and task parallelism and the scheduling trade-offs between them.
- “Rust Atomics and Locks” by Mara Bos (O’Reilly, 2023):
std::thread::scopeand why a disjoint split needs nounsafeonce the borrow checker can see it.