C++ · 6 · Concurrency29 / 36 · 81%
jthread, stop_token & Coroutines
C++20's answer to "I forgot to join" and to callback-heavy async code.
Examples: jthread, stop_token, co_await, co_yield
shortcuts: ← prev · → next · M mark
1
std::jthread
Joins automatically in its destructor and supports cooperative cancellation.
Example
example
std::jthread worker([](std::stop_token st) {
while (!st.stop_requested()) {
do_chunk();
}
});
// worker.request_stop() then join() happen automatically at scope exitstd::thread
| case | result |
|---|---|
| forgot join() | std::terminate |
| exception thrown | terminate |
| cancellation | roll your own |
std::jthread
| case | result |
|---|---|
| scope exit | auto join |
| exception | auto join |
| cancellation | stop_token |
2
Cooperative Cancellation
There is no safe way to kill a thread — you ask it to stop.
Example
example
void worker(std::stop_token st) {
std::stop_callback cb(st, []{ std::puts("stopping"); });
while (!st.stop_requested()) { step(); }
}3
Coroutines
A function that can suspend and resume — the compiler rewrites it into a state machine.
Example
example
Generator<int> fibonacci() {
int a = 0, b = 1;
while (true) {
co_yield a; // suspend, hand a value out
auto next = a + b; a = b; b = next;
}
}
Task<Response> fetch(Url u) {
auto conn = co_await connect(u); // suspend without blocking a thread
co_return co_await conn.read();
}WATCH OUT
C++20 ships the language machinery but almost no library types — you write or import Task/Generator (C++23 adds std::generator).
4
When to Use What
Match the tool to the workload.
Complexity
| jthread | CPU-bound parallelism | |
| async/future | one-off background result | |
| thread pool | many short tasks | |
| coroutines | I/O-bound concurrency | thousands of in-flight ops |