bhylu.com

Advertisements

C++ Threads

Use jthread for scoped ownership of a thread and synchronize access before observing shared state.

How it works

std::jthread owns a thread and joins it on destruction when joinable, also offering cooperative stop requests. Joining establishes the synchronization needed to observe completed worker writes from the joining thread. This small example has one writer and the main thread reads only after join, so no mutex is needed for that particular access pattern. Detaching a worker would remove the simple lifetime relationship and could let it outlive its captured references. Thread creation can fail and a worker’s uncaught exception terminates the process.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror threads.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Environment boundary: Requires a C++20 standard library with jthread support. Some GCC/Clang platforms also require a thread-linking option such as -pthread.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · threads.cpp

#include <iostream>
#include <thread>

int main() {
    int result{0};
    std::jthread worker{[&result] { result = 6 * 7; }};
    worker.join();
    std::cout << "Worker result: " << result << '\n';
}

Expected result

Worker result: 42

The local result remains alive until after the worker is joined. The output happens in one thread after completion, making its order deterministic. A stop request is cooperative: code using a stop_token must actually observe it and leave according to its contract. This executed fixture checks the simple join relationship, not a scheduler stress test or a complete cancellation service.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.

Advertisements