Table of Contents

<thread>

<thread> provides std::thread for creating and managing threads, and std::jthread (C++20) which automatically joins on destruction. Create a thread by passing a callable and arguments; join to wait for completion.

Use std::jthread in new code when available; it prevents accidental detached threads.

Example

This example creates two threads that run concurrently, each printing a message, then waits for both to complete.

// compile: g++ -std=c++11 -pthread -o threadexample threadexample.cpp
// run: ./threadexample
// description: create and join threads
 
#include <thread>
#include <iostream>
 
void worker(int id) {
    std::cout << "thread " << id << " working\n";
}
 
int main() {
    std::thread t1(worker, 1);
    std::thread t2(worker, 2);
 
    t1.join();
    t2.join();
 
    std::cout << "all threads done\n";
 
    return 0;
}