Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

Async & concurrency

TypeScript promises, Go goroutines/context, Rust futures with Tokio where named, and C++ threads/futures. Runtime and cancellation rules differ; optional setup is identified in each entry.

Create async work

C++

std::async with launch::async runs a callable asynchronously and returns a future. A C++ coroutine is a different mechanism: C++23 supplies coroutine machinery, but no general executor or standard co_await support for std::future.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <future>

auto pending = std::async(std::launch::async, [] {
    return 42;
});

Include <future>. With no explicit launch policy, execution may be deferred. A future associated with std::async can wait during destruction.

Wait for a value

C++

future::get waits on the current thread, retrieves the result once and rethrows a stored exception. It is a blocking wait, not coroutine suspension.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <future>

auto value = pending.get();

Include <future>. A shared_future supports multiple readers under its documented result/lifetime rules.

Retain ownership of a background task

C++

jthread owns a thread, requests cooperative stop and joins during destruction. Keep the object in the scope that owns the work; an uncaught exception escaping a thread function terminates the program.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <thread>

std::jthread task([] {
    work();
});
task.join();

Include <thread>. work must handle its failures or communicate them to the owner.

Sequential awaits versus overlapping work

C++

Launch both operations before getting either result to overlap their work. Two get calls on already-started futures do not serialize their start.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <future>

auto left = std::async(std::launch::async, load_left);
auto right = std::async(std::launch::async, load_right);
auto a = left.get();
auto b = right.get();

Include <future>. This requests separate asynchronous executions, not a bounded thread pool.

Let other work progress

C++

this_thread::yield suggests that the scheduler run other threads. It neither waits for a particular thread nor establishes synchronization.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <thread>

std::this_thread::yield();

Include <thread>. Do not build a correctness protocol around a yield or guessed delay.

Wait for all successful results

C++

The standard library has no Promise.all-shaped operation over arbitrary futures. Retain every future and retrieve each outcome; an exception from one get does not cancel the others.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <future>

for (auto& task : tasks) {
    consume(task.get());
}

Include <future>. This simple loop stops on an exception; use the collect-all-outcomes pattern when every failure must be observed.

Collect successes and failures

C++

Observe each future in its own try/catch so one failure does not skip the remaining outcomes. Stored exceptions are rethrown by get.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <exception>
#include <future>

for (auto& task : tasks) {
    try { record_value(task.get()); }
    catch (...) { record_error(std::current_exception()); }
}

Include <future> and <exception>. record_value and record_error are application-defined sinks.

Propagate async/task failures

C++

get rethrows an exception stored by std::async or a promise. Recover or propagate from the owning thread; a raw jthread does not automatically store exceptions.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <exception>
#include <future>

try {
    auto value = pending.get();
    consume(value);
} catch (const std::exception& error) {
    report(error.what());
    throw;
}

Include <future> and <exception>.

Clean up after asynchronous work

C++

RAII releases a scoped guard on return and exception unwinding. Resource ownership still needs a lifetime that covers every worker using it.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <mutex>

{
    std::lock_guard lock(mutex);
    update_shared_state();
} // Unlocks even if update_shared_state throws.

Include <mutex>. Do not hold an unrelated lock while waiting for slow work or joining a thread that needs it.

Request cancellation

C++

request_stop is a cooperative signal; work must check a stop_token or use a stop-aware wait. std::future has no general cancel member.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <stop_token>
#include <thread>

std::jthread worker([](std::stop_token stop) {
    while (!stop.stop_requested()) {
        do_one_bounded_unit();
    }
});
worker.request_stop();
worker.join();

Include <thread> and <stop_token>. The application-defined unit must return; stop does not interrupt arbitrary blocking I/O.

Bound the duration of work

C++

wait_for reports readiness or timeout. It does not cancel the operation, and destruction of a future from std::async can still wait for completion.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <chrono>
#include <future>

auto status = pending.wait_for(std::chrono::seconds(3));
if (status == std::future_status::timeout) {
    report_timeout();
}

Include <future> and <chrono>. A deferred future can report deferred; design cooperative stopping and owned joining separately.

Wait for the first completion

C++

C++23 has no standard when_any or select over arbitrary futures. Choose a documented task/async library, or design a completion queue whose workers report to an owner. A losing operation still needs an explicit lifetime and cancellation policy.

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

Polling wait_for in a busy loop is not a substitute for an owned completion protocol.

Delay work with the runtime’s timer model

C++

this_thread::sleep_for blocks the calling thread for at least the requested duration, subject to the clock/scheduler. C++23 has no general standard executor timer that suspends a coroutine.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <chrono>
#include <thread>

std::this_thread::sleep_for(std::chrono::milliseconds(100));

Include <thread> and <chrono>. Use the chosen async library’s timer inside its executor.

Send a value through a channel

C++

promise/future can communicate one result or exception. They are not a reusable multi-message channel with a buffer and close operation.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <future>
#include <thread>

std::promise<int> sender;
auto receiver = sender.get_future();
std::jthread producer([&sender] { sender.set_value(42); });
auto value = receiver.get();
producer.join();

Include <future> and <thread>. The producer completes before sender leaves scope.

Distinguish channel closure from a value

C++

A promise abandoned before supplying a result makes its future observe broken_promise. This is not the same contract as a drained Go/Tokio channel; a reusable queue needs a separately defined closed state.

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

Include <future> when handling future_error and future_errc::broken_promise.

Recognize a backpressure boundary

C++

C++23 has counting_semaphore but no standard bounded channel. A producer can acquire capacity before submitting work; the worker must release that capacity on every exit path.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <semaphore>

std::counting_semaphore<4> capacity(4);
capacity.acquire();
// Submit work with an RAII permit that releases capacity.
// If submission fails, release the acquired permit here.

Include <semaphore>. This is a protocol sketch, not a complete queue. Prefer a library’s bounded queue when you need close, cancellation and error handling.

Consume a stream incrementally

C++

Standard stream extraction is incremental but blocking. A network library’s asynchronous stream has its own executor and cancellation contract.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <istream>
#include <string>

for (std::string line; std::getline(input, line);) {
    consume(line);
}

Include <istream> and <string>. input is an existing std::istream; getline removes its delimiter.

Limit concurrent operations

C++

A fixed set of workers can claim indices atomically. Each index is reserved once; concurrent reads of items and the process function must be safe. Catch/report errors inside each thread.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <atomic>
#include <thread>
#include <vector>

std::atomic_size_t next{0};
std::vector<std::jthread> workers;
for (int worker = 0; worker < 4; ++worker) {
    workers.emplace_back([&] {
        for (;;) {
            auto i = next.fetch_add(1);
            if (i >= items.size()) return;
            process(items[i]);
        }
    });
}
for (auto& worker : workers) worker.join();

Include <atomic>, <vector> and <thread>. This sketch assumes process does not throw across the thread boundary and items stays unchanged until joining finishes.

Protect a shared invariant

C++

A mutex protects an invariant only if every reader/writer follows the same locking protocol. lock_guard releases on all ordinary scope exits.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <mutex>

std::mutex mutex;
{
    std::lock_guard lock(mutex);
    ++count;
}

Include <mutex>. mutex and count must be the same shared objects used by every participant.

Move blocking or CPU-heavy work appropriately

C++

A thread can run CPU work independently of the calling thread. Async syntax alone does not supply a bounded pool or make shared data safe.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <thread>

std::jthread worker([input] {
    compute(input);
});
worker.join();

Include <thread>. Bound the worker count and transfer/capture inputs under an explicit ownership policy.

Separate shared ownership from synchronization

C++

shared_ptr shares ownership, while atomic/mutex supplies a synchronization protocol. Sharing an ordinary mutable object through shared_ptr alone is not race-safe.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <atomic>
#include <memory>

auto count = std::make_shared<std::atomic<int>>(0);
count->fetch_add(1, std::memory_order_relaxed);

Include <memory> and <atomic>. relaxed keeps this increment atomic but imposes no ordering on other memory operations, so it does not publish unrelated data.

Keep child work inside an owned lifetime

C++

A scoped jthread joins on destruction. Declare shared resources before the workers that use them, so workers finish before those resources are destroyed.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <thread>

SharedState shared;
{
    std::jthread worker([&] { work(shared); });
} // worker is joined before shared can be destroyed.

Include <thread>. SharedState/work are application-defined; a blocked worker can make scope exit wait indefinitely.

Establish the runtime and API baseline

C++

Standard C++ threads/futures need no Tokio-style runtime. Coroutines require a suitable return type and scheduling/awaitable implementation; the language keyword is not a complete async framework.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <thread>
#include <atomic>
#include <iostream>
int main() {
    std::atomic<int> count{0};
    std::jthread worker([&] { count.fetch_add(1); });
    worker.join();
    std::cout << count.load() << '\n';
}

Use a C++20+ toolchain; thread-linking flags such as -pthread depend on the target/toolchain.

Cancel cooperating siblings and observe completion

C++

A stop_source can distribute a cooperative request to tasks that were given its token. Catch each future’s exception, request stop, observe all futures and then rethrow the first failure.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <exception>
#include <future>
#include <stop_token>

std::exception_ptr first_error;
for (auto& task : tasks) {
    try { consume(task.get()); }
    catch (...) {
        if (!first_error) first_error = std::current_exception();
        stop.request_stop();
    }
}
if (first_error) std::rethrow_exception(first_error);

Include <future>, <exception> and <stop_token>. tasks were already started with stop.get_token(); consume must have a deliberate failure policy too.

Bound task records and consume results while launching

C++

A small future window bounds retained task records. Retrieve and discard a record as the window fills; input-order retrieval can wait behind a slow earlier task.

Fragment

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <deque>
#include <future>

std::deque<std::future<Value>> pending;
for (auto item : items) {
    if (pending.size() == 4) {
        consume(pending.front().get());
        pending.pop_front();
    }
    pending.push_back(std::async(std::launch::async,
        [item] { return work(item); }));
}
for (auto& task : pending) consume(task.get());

Include <deque> and <future>. Value/work/consume are application-defined. This simple success-path recipe still needs an error/stop policy; std::async is not a pooled scheduler.

Account for progress when a wait is canceled

C++

Stopping a wait does not undo side effects or partially completed I/O. A stop_token only has meaning where the operation cooperates; preserve progress before choosing whether to retry.

C++20/23. Code fragments assume an enclosing function, named application values and the indicated standard headers.

A timed-out future can still produce a result later. C++23 has no universal cancellation-safe I/O contract.