Skip to content
AgileLogics
5 min read

Concurrency with std::thread

Prerequisites: Ranges (C++20)

std::thread (C++11) wraps the platform's native threading, giving a portable, RAII-friendly API — replacing the raw pthread calls used in Learn C's advanced lessons:

#include <thread>

void printNumbers() {
    for (int i = 0; i < 3; i++) {
        std::cout << "Thread: " << i << std::endl;
    }
}

int main() {
    std::thread t(printNumbers);
    t.join(); // wait for it to finish
    return 0;
}

Common mistakes

  • Letting a std::thread object be destroyed while still joinable() (neither .join()ed nor .detach()ed) — this calls std::terminate, crashing the program immediately.