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.

Libraries: concurrency & network

Doing several things at once and talking to other machines: threads and tasks, locks and atomics, CPU parallelism, event loops, cancellation, request context, sockets, TLS and HTTP.

Concurrency: Promise, sync + goroutines, std::thread/std::sync, <thread>

C++

<thread> starts operating-system threads (std::jthread, from C++20, joins automatically and supports stop requests), <mutex> provides std::mutex with RAII lock guards, <atomic> has lock-free counters, <condition_variable> handles waiting, and <future> offers std::async and std::future for a value computed on another thread. There is no standard thread pool or async I/O runtime yet; Boost.Asio is the common choice.

Complete program

Complete program. Standard library: ships with your compiler, no install.

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

int fetch_price(int id) {
    std::this_thread::sleep_for(std::chrono::milliseconds(10 * id)); // stands in for I/O
    return id * 100;
}

int main() {
    std::map<int, int> prices;
    std::mutex mu;
    {
        std::vector<std::jthread> workers; // jthread joins when destroyed
        for (int id : {1, 2, 3}) {
            workers.emplace_back([&, id] {
                int price = fetch_price(id);
                std::lock_guard lock(mu);
                prices[id] = price;
            });
        }
    } // all workers have joined here

    auto future = std::async(std::launch::async, fetch_price, 4);
    std::println("{} {}", prices.size(), future.get());
}

Most used: std::jthread, std::thread::join, std::mutex with std::lock_guard or std::scoped_lock, std::atomic, std::async, std::future::get.

Locks, atomics & one-time init: Atomics, sync.Once, OnceLock, std::call_once

C++

<mutex> has std::mutex and RAII locks: std::scoped_lock locks one or several mutexes (several without deadlock), and std::unique_lock adds deferred locking and works with condition variables. std::shared_mutex with std::shared_lock gives reader-writer locking. std::atomic<T> makes single values lock-free, with std::memory_order arguments for weaker ordering. A function-local static is initialised exactly once, thread-safely, and std::call_once with a std::once_flag does the same for any code. C++20 added std::latch (a one-shot countdown), std::barrier (reusable, per phase) and std::counting_semaphore.

Complete program

Complete program. Standard library: ships with your compiler, no install.

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

const std::string& region() {
    static const std::string value = [] { // initialised once, thread-safely (C++11+)
        std::println("loading region");
        return std::string("eu");
    }();
    return value;
}

class Inventory {
    mutable std::shared_mutex mu;
    int stock = 5;

public:
    bool take() {
        std::scoped_lock lock(mu); // exclusive: one writer
        if (stock == 0) return false;
        --stock;
        return true;
    }
    int count() const {
        std::shared_lock lock(mu); // shared: many readers
        return stock;
    }
};

int main() {
    Inventory inventory;
    std::atomic<int> taken = 0;
    std::once_flag audit;
    std::latch start(8); // a one-shot countdown
    {
        std::vector<std::jthread> workers;
        for (int i = 0; i < 8; ++i)
            workers.emplace_back([&] {
                start.arrive_and_wait(); // all eight begin together
                std::call_once(audit, [] { std::println("audit opened"); }); // others wait for it
                region();
                if (inventory.take()) taken.fetch_add(1, std::memory_order_relaxed);
            });
    } // jthreads join here
    std::println("{} taken: {} left: {}", region(), taken.load(), inventory.count());
}

Most used: std::mutex, std::scoped_lock, std::unique_lock, std::shared_mutex, std::shared_lock, std::atomic fetch_add and load, std::memory_order_relaxed, function-local static, std::call_once, std::latch, std::barrier, std::counting_semaphore.

Lock several mutexes with one std::scoped_lock(a, b) instead of nesting locks, or take them in one fixed order everywhere; inconsistent order deadlocks.

std::mutex is not recursive: locking it twice from one thread is undefined behaviour.

Atomics written by different threads that sit in one cache line slow each other down (false sharing); alignas(std::hardware_destructive_interference_size) separates them.

A data race on a non-atomic variable is undefined behaviour; build with -fsanitize=thread to find one.

CPU parallelism & worker pools: worker_threads, errgroup, rayon, std::jthread

C++

The standard has no thread pool yet, so parallel work is a set of std::jthread workers sized by std::thread::hardware_concurrency() (which may return 0 when unknown), each writing its own result. C++17 execution policies (std::execution::par, par_unseq) parallelise std::reduce, std::for_each, std::sort and other algorithms, but support depends on the library: Apple clang’s libc++ does not provide them at all, recent LLVM libc++ (Homebrew llvm, for example) ships them only behind -fexperimental-library, and GCC’s libstdc++ needs Intel TBB (link -ltbb) or it runs sequentially. Intel oneTBB, OpenMP (#pragma omp parallel for) and Boost.Asio’s thread_pool are the usual libraries.

Complete program

Complete program. Standard library: ships with your compiler, no install.

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

bool is_prime(unsigned n) {
    if (n < 2) return false;
    for (unsigned d = 2; d * d <= n; ++d)
        if (n % d == 0) return false;
    return true;
}

int main() {
    const unsigned limit = 200'000;
    const unsigned threads = std::max(1u, std::thread::hardware_concurrency()); // 0 means unknown
    const unsigned size = (limit + threads - 1) / threads;
    std::vector<unsigned> counts(threads); // one slot per thread: no lock
    {
        std::vector<std::jthread> pool;
        for (unsigned t = 0; t < threads; ++t)
            pool.emplace_back([&, t] {
                unsigned local = 0; // count locally: neighbouring slots share a cache line
                for (unsigned n = t * size; n < std::min(limit, (t + 1) * size); ++n)
                    local += is_prime(n);
                counts[t] = local;
            });
    } // every jthread joins here
    std::println("primes below {} = {}", limit, std::reduce(counts.begin(), counts.end()));
}

Most used: std::jthread, std::thread::hardware_concurrency, std::reduce, std::execution::par with std::for_each or std::reduce where supported, oneTBB parallel_for, OpenMP, boost::asio::thread_pool.

Accumulating into neighbouring vector elements from different threads makes them fight over one cache line (false sharing); count in a local variable and store once, as the example does.

An exception escaping a std::thread or std::jthread function calls std::terminate; catch inside the worker, or use std::async, whose future rethrows on get().

Event loops & async runtimes: EventEmitter, the Go scheduler, tokio, Asio

C++

The C++ standard has coroutines (co_await) but no event loop or async I/O. Boost.Asio (also available standalone) provides the common one: an io_context runs queued handlers, asio::post queues work, and timers, sockets and signals deliver completion events; C++20 coroutines (asio::awaitable with co_spawn) let asynchronous code read sequentially. libuv (behind Node.js) and libevent are C alternatives.

Complete program

Complete program.

Before you use this

Not in the standard library: Boost.Asio (header-only, Boost 1.70+) or standalone Asio.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <boost/asio.hpp>
#include <chrono>
#include <print>

namespace asio = boost::asio;

int main() {
    asio::io_context io; // the event loop: runs queued handlers one at a time

    for (int id = 7; id < 10; ++id)
        asio::post(io, [id] { std::println("received {}", id); }); // queue work

    asio::steady_timer timer(io, std::chrono::milliseconds(10));
    timer.async_wait([](boost::system::error_code error) { // a timer event
        if (!error) std::println("drained");
    });

    io.run(); // returns when no work is left
}

Most used: asio::io_context, run, asio::post, steady_timer::async_wait, co_spawn with asio::awaitable, use_awaitable, strand, thread_pool.

Cancellation & deadlines: AbortController, context, CancellationToken, std::stop_token

C++

C++20 added cooperative cancellation: std::jthread owns a std::stop_source and passes a std::stop_token to its function, request_stop() asks it to finish, and std::stop_callback runs code when a stop is requested. The work must check stop_requested() itself; nothing is interrupted. std::future::wait_for and condition_variable_any::wait with a stop token put deadlines on waiting, not on the work: a future from std::async blocks in its destructor until the task finishes, and Boost.Asio cancels asynchronous operations through cancellation slots and timers.

Complete program

Complete program. Standard library: ships with your compiler, no install.

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

using namespace std::chrono_literals;

// Long-running work checks its stop token between steps.
void fetch_report(std::stop_token stop) {
    for (int step = 0; step < 100; ++step) {
        if (stop.stop_requested()) {
            std::println("stopped early, after {} of 100 steps", step);
            return;
        }
        std::this_thread::sleep_for(10ms); // stands in for slow I/O
    }
    std::println("report ready");
}

int main() {
    std::jthread worker(fetch_report); // jthread passes a stop_token as the first argument
    std::this_thread::sleep_for(50ms);
    worker.request_stop(); // cancel by hand (the destructor also does this)
    worker.join();

    auto slow = [] {
        std::this_thread::sleep_for(100ms);
        return 42;
    };
    auto result = std::async(std::launch::async, slow);
    if (result.wait_for(20ms) == std::future_status::timeout) // a deadline on waiting
        std::println("still running after 20 ms"); // ~destructor of result waits for it
}

Most used: std::jthread, std::stop_token, stop_requested, request_stop, std::stop_callback, std::future::wait_for, condition_variable_any::wait with a token.

Request-scoped context: AsyncLocalStorage, context.WithValue, task_local!, thread_local

C++

C++ has no standard way to carry a value through asynchronous work. thread_local gives each thread its own variable, which is enough when one thread handles one request from start to finish; an RAII guard that sets and restores it keeps the value scoped. Once work hops between threads (a thread pool, std::async, coroutines resumed elsewhere) a thread_local shows the wrong thread’s value, so pass a context object explicitly as a parameter. Frameworks add their own: OpenTelemetry C++ keeps a runtime context, and Boost.Asio associates data with handlers.

Complete program

Complete program. Standard library: ships with your compiler, no install.

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

struct RequestContext {
    std::string request_id;
    std::string user;
};

thread_local const RequestContext* current = nullptr; // one pointer per thread

class ScopedContext { // sets this thread's context, restores the previous one on exit
    const RequestContext* previous;

public:
    explicit ScopedContext(const RequestContext& ctx) : previous(current) { current = &ctx; }
    ~ScopedContext() { current = previous; }
    ScopedContext(const ScopedContext&) = delete;
    ScopedContext& operator=(const ScopedContext&) = delete;
};

void log(std::string_view message) {
    std::println("[{}] {}", current ? std::string_view(current->request_id) : "-", message);
}

// Explicit passing works on any thread; prefer it when work changes threads.
void load_orders(const RequestContext& ctx) { log(std::format("orders for {}", ctx.user)); }

int main() {
    std::jthread([] {
        RequestContext ctx{"r1", "ada"};
        ScopedContext scope(ctx);
        log("start");
        load_orders(ctx);
    }).join();
    log("outside"); // the main thread never saw r1
}

Most used: thread_local, an RAII guard that sets and restores it, a context struct passed by const reference, opentelemetry::context::RuntimeContext.

A coroutine that suspends on one thread and resumes on another sees the second thread’s thread_local values.

Every thread_local with a non-trivial constructor is initialised per thread on first use and destroyed when that thread exits, which adds cost to short-lived threads.

TCP & UDP sockets: node:net, net, std::net, Boost.Asio

C++

The C++ standard library has no networking yet. Boost.Asio (or standalone Asio) is the usual choice: io_context runs I/O, tcp::acceptor and tcp::socket handle TCP, and every operation exists in a blocking form (shown) and an asynchronous form that uses callbacks or C++20 coroutines. POSIX sockets (socket, bind, listen, accept) are the low-level alternative, and libuv is the C event loop behind Node.

Complete program

Complete program.

Before you use this

Not in the standard library: Boost.Asio (header-only, Boost 1.70+) or standalone Asio.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <boost/asio.hpp>
#include <iostream>
#include <string>
#include <thread>

using boost::asio::ip::tcp;

int main() {
    boost::asio::io_context io;
    tcp::endpoint local{boost::asio::ip::make_address("127.0.0.1"), 0}; // port 0: a free port
    tcp::acceptor acceptor(io, local);

    std::jthread server([&] { // an echo server for one connection
        tcp::socket socket = acceptor.accept();
        std::string line;
        boost::asio::read_until(socket, boost::asio::dynamic_buffer(line), '\n');
        boost::asio::write(socket, boost::asio::buffer(line));
    });

    tcp::socket client(io);
    client.connect(acceptor.local_endpoint());
    boost::asio::write(client, boost::asio::buffer(std::string("ping\n")));
    std::string reply;
    boost::asio::read_until(client, boost::asio::dynamic_buffer(reply), '\n');
    std::cout << "echoed: " << reply;
}

Most used: io_context, tcp::acceptor, accept, tcp::socket, connect, read_until, write, async_read with co_await, udp::socket, ssl::stream.

TLS & certificates: node:tls, crypto/tls + crypto/x509, rustls, OpenSSL

C++

The C++ standard library has no TLS. OpenSSL is the usual library (BoringSSL, LibreSSL and wolfSSL offer similar APIs, and Boost.Asio's ssl::stream wraps OpenSSL). A client creates an SSL_CTX, turns on peer verification and loads trusted roots, then for each connection sets the SNI name and the expected host name before SSL_connect. Both name settings are separate, and OpenSSL checks neither the chain nor the name unless you ask: SSL_VERIFY_PEER with SSL_CTX_set_default_verify_paths (or SSL_CTX_load_verify_locations for a private CA), and SSL_set1_host for the name.

Complete program

Complete program; needs network access to example.com.

Before you use this

Not in the standard library: OpenSSL 3 (link with -lssl -lcrypto). With Homebrew: -I/opt/homebrew/opt/openssl@3/include -L/opt/homebrew/opt/openssl@3/lib.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <cstdio>
#include <print>
#include <string_view>

int main() {
    SSL_CTX* ctx = SSL_CTX_new(TLS_client_method());
    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, nullptr); // the default is SSL_VERIFY_NONE
    SSL_CTX_set_default_verify_paths(ctx);             // the CA bundle OpenSSL was built with
    SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);

    BIO* tcp = BIO_new_connect("example.com:443");
    if (BIO_do_connect(tcp) <= 0) return 1;
    SSL* ssl = SSL_new(ctx);
    SSL_set_bio(ssl, tcp, tcp);                  // ssl now owns the BIO
    SSL_set_tlsext_host_name(ssl, "example.com"); // SNI
    SSL_set1_host(ssl, "example.com");            // the name the certificate must match

    if (SSL_connect(ssl) != 1) { // fails on a bad chain or a wrong name
        ERR_print_errors_fp(stderr);
        return 1;
    }
    X509* cert = SSL_get1_peer_certificate(ssl);
    char subject[256];
    X509_NAME_oneline(X509_get_subject_name(cert), subject, sizeof subject);
    std::println("{} {} {}", SSL_get_version(ssl), SSL_get_verify_result(ssl) == X509_V_OK,
                 std::string_view(subject)); // a plain char array would print all 256 bytes

    X509_free(cert);
    SSL_shutdown(ssl);
    SSL_free(ssl);
    SSL_CTX_free(ctx);
}

Most used: SSL_CTX_new(TLS_client_method()), SSL_CTX_set_verify(SSL_VERIFY_PEER), SSL_CTX_set_default_verify_paths, SSL_CTX_set_min_proto_version, BIO_new_connect, SSL_set_tlsext_host_name, SSL_set1_host, SSL_connect, SSL_get_verify_result, SSL_get1_peer_certificate, SSL_read and SSL_write.

The default for a new SSL_CTX is SSL_VERIFY_NONE, and SSL_VERIFY_NONE outside a test means any certificate is accepted: an attacker on the network path can impersonate the server and read the traffic. Without SSL_set1_host, a valid certificate for any other site is accepted too.

Output depends on the server: example.com currently negotiates TLS 1.3.

HTTP: fetch + node:http, net/http, reqwest/axum, cpp-httplib

C++

The C++ standard library has no networking or HTTP. cpp-httplib is a single-header client and server that is easy to start with; Boost.Beast (on Boost.Asio) and Drogon suit larger services, and libcurl is the long-standing client. Each has to be added through your package manager or vendored into the project.

Complete program

Complete program that needs network access; it keeps serving until stopped.

Before you use this

Not in the standard library: cpp-httplib (header-only) from vcpkg, Conan or a vendored httplib.h. HTTPS also needs OpenSSL.

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

int main() {
    // Client: plain HTTP here; HTTPS needs CPPHTTPLIB_OPENSSL_SUPPORT and OpenSSL.
    httplib::Client client("http://example.com");
    if (auto result = client.Get("/")) std::println("{}", result->status);

    // Server
    httplib::Server server;
    server.Get(R"(/orders/(\d+))", [](const httplib::Request& req, httplib::Response& res) {
        res.set_content("{\"id\": " + req.matches[1].str() + "}", "application/json");
    });
    server.listen("0.0.0.0", 8080);
}

Most used: httplib::Client::Get/Post, httplib::Server::Get/Post with a lambda handler, req.matches for path captures, res.set_content, server.listen.