Start Threads in C++ with std::thread and std::jthread
Launch threads in C++ with std::thread and the C++20 std::jthread, which joins automatically. Covers arguments, references, join rules and std::terminate.

C++11 gave the language a thread type, std::thread, and it shipped with a trap: if a std::thread object is destroyed while it still owns a running thread, the program calls std::terminate. C++20 added std::jthread, which closes the trap by joining in its destructor. Both are thin wrappers over the operating system's threads, so on Linux with libstdc++ they sit on top of pthreads. This post covers launching threads with each, passing arguments (including the reference surprise), and handling the lifetime rules, using GCC 15 with -std=c++20. If the underlying C API is new to you, the pthread_create post shows what these classes wrap.
A first thread with std::thread
Include <thread>, construct a std::thread with a callable, and join it:
#include <iostream>
#include <thread>
void greet()
{
std::cout << "hello from the worker\n";
}
int main()
{
std::thread worker(greet);
worker.join();
std::cout << "worker finished\n";
}Build with g++ -std=c++20 -Wall -Wextra -pthread -o hello_thread hello_thread.cpp:
hello from the worker
worker finishedThe thread starts running as soon as the constructor returns, possibly before the next line of main. join() blocks until it is done. A std::thread that has been constructed with a callable is called joinable, and joinable() reports it. It becomes non-joinable after join(), after detach(), after being moved from, or if it was default-constructed.
The std::terminate trap
Remove the join() line and the program does not print "worker finished" at all. It aborts. The standard requires that destroying a joinable std::thread calls std::terminate, and with libstdc++ the process prints this and dies from SIGABRT:
terminate called without an active exception
Aborted (core dumped)(The worker's greeting may or may not appear first, since it races with the abort.) The rule exists because the alternatives, silently joining or silently detaching, both hide bugs: joining can block forever in a destructor, and detaching can leave a thread running against objects that no longer exist. The committee chose a loud failure.
The consequence is that any early return or exception between construction and join() is a bug:
std::thread worker(work);
do_something_that_throws(); // worker is destroyed while joinable: terminate
worker.join();Before C++20 you wrote a small RAII guard class to call join() in its destructor. Now you can use std::jthread.
std::jthread joins for you
std::jthread (C++20, header <thread>) has the same constructor and the same members, plus two changes: its destructor requests a stop and then joins, and it supports cooperative cancellation through std::stop_token.
#include <iostream>
#include <thread>
void greet(int id)
{
std::cout << "worker " << id << " says hello\n";
}
int main()
{
{
std::jthread worker(greet, 1);
} // destructor joins here
std::cout << "worker finished\n";
}worker 1 says hello
worker finishedThe inner scope ends, ~jthread joins, and only then does the next line run. If the scope is left by an exception, the join still happens. For code that owns threads as members of a class, std::jthread is the right default in C++20: the class destructor cleans up without a hand-written join.
The cooperative stop is covered in detail in stopping C++ threads with std::stop_token. One thing worth knowing here: if the callable's first parameter is a std::stop_token, jthread passes its own token automatically, and that is the only difference in how you write the function.
Passing arguments
Extra constructor arguments are forwarded to the callable. Each one is decay-copied (or moved) into storage owned by the thread before it starts, so the new thread works on its own copy:
#include <iostream>
#include <string>
#include <thread>
void describe(int count, std::string label)
{
std::cout << label << ": " << count << '\n';
}
int main()
{
std::string label = "items";
std::jthread t(describe, 3, label);
}items: 3Because the arguments are copied, a plain reference parameter does not behave the way you expect:
void add_one(int &x) { ++x; }
int n = 0;
std::thread t(add_one, n); // does not compileGCC rejects this with an error from inside <thread> along the lines of static assertion failed: std::thread arguments must be invocable after conversion to rvalues. The copy made for the thread is an rvalue, and it cannot bind to int &. When you do want the thread to modify your variable, say so with std::ref:
#include <functional>
#include <iostream>
#include <thread>
void add_one(int &x) { ++x; }
int main()
{
int n = 0;
std::jthread t(add_one, std::ref(n));
t.join();
std::cout << "n = " << n << '\n';
}n = 1The explicit t.join() before reading n matters. Reading n while the thread may still be writing it is a data race, which is undefined behavior. The destructor would join, but only at the end of main, after the read. You also take on responsibility for lifetime: n must outlive the thread, which here it does because t is destroyed first (locals are destroyed in reverse order of construction).
Lambdas and member functions
A lambda is the most readable way to start a thread, because it can capture exactly what it needs:
#include <iostream>
#include <thread>
#include <vector>
int main()
{
std::vector<int> results(3);
std::vector<std::jthread> workers;
for (int i = 0; i < 3; ++i) {
workers.emplace_back([&results, i] {
results[i] = (i + 1) * 100;
});
}
workers.clear(); // destroys every jthread, joining each one
for (int v : results)
std::cout << v << '\n';
}100
200
300Each thread writes to a different element, so there is no race. Clearing the vector of jthread objects joins them all before the results are read. Capturing i by value and results by reference is deliberate: capturing i by reference would give every thread a view of a variable that the loop keeps changing.
For a member function, pass the member pointer and the object:
struct Counter { void run(int n); };
Counter c;
std::jthread t(&Counter::run, &c, 10);&c is a pointer, so the thread uses the original object. Passing c itself would copy it.
Getting a result back
std::thread has no return channel; the function's return value is discarded. Use a captured variable as above, a std::promise and std::future, or std::async, which returns a future directly. For failures inside a worker, see propagating exceptions with std::exception_ptr. An exception that escapes the thread's function does not propagate to the creator; it calls std::terminate.
Platform notes
std::thread::hardware_concurrency() returns a hint about the number of concurrent threads the hardware supports, or 0 when it cannot tell, so treat 0 as "unknown". On Linux with GCC, link with -pthread; glibc 2.34 merged libpthread into libc, which hides the missing flag on new systems and makes it a link error on older ones.
Choosing between thread, jthread and async
Three tools cover most needs. Use std::jthread when you want a worker with a lifetime tied to a scope or an object: a background logger owned by a class, a pool of workers owned by a server object. Use std::async with std::launch::async when you want one result from one computation and the exception handling that comes with a future, as in the pattern for propagating exceptions. Use plain std::thread only when you must call detach() or support a standard older than C++20.
One more rule applies to all of them: the thread starts running before the constructor returns, so everything the new thread reads must be fully constructed first. A class that starts a jthread in its constructor, from a member initializer, can have the thread run against members that have not been initialized yet, because members are initialized in declaration order. Declare the thread member last, or start it in a separate start() method called after construction. The destructor order then also joins the thread before the members it uses are destroyed.


