std::thread — represents a thread of execution. Must be joined or detached.
1#include <thread>2#include <iostream>34void worker(int id) {5 std::cout << "Thread " << id << "\n";6}78int main() {9 // Create and run thread10 std::thread t1(worker, 1);1112 // Lambda13 std::thread t2([]{14 std::cout << "Lambda thread\n";15 });1617 // Must join or detach18 t1.join();19 t2.join();2021 // Hardware concurrency22 std::cout << std::thread::hardware_concurrency();2324 return 0;25}2627// C++20: std::jthread (auto-join)28std::jthread jt([](std::stop_token stoken) {29 while (!stoken.stop_requested()) {30 // Work31 }32});33// Auto-joined on destruction
Rules: