Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Concurrency

C++ std::thread class

Reference for std::thread: start a thread, pass arguments and references, join or detach, get the id, and avoid the terminate-on-destruction trap.

std::thread (header <thread>) represents one thread of execution. You construct it with a callable and its arguments; the new thread starts running immediately. Before the thread object is destroyed you must either join() it (wait for the thread to finish) or detach() it (let it run on its own). If you do neither, the destructor calls std::terminate() and the program ends.

Arguments are copied (or moved) into the new thread. To give the thread a reference to a variable, wrap it in std::ref. Threads share the program's memory, so any data that more than one thread touches, with at least one write, needs a mutex or an atomic. Link with -pthread on Linux (the runner already does).

C++
std::thread t([] { std::cout << "hello from a thread\n"; });
t.join();

Try it

C++ Start, pass arguments, join

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ joinable, ids and moving

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
template<class F, class... Args> explicit thread(F&& f, Args&&... args);
thread() noexcept;                       // no thread
thread(thread&&) noexcept;               // move only
void join();      void detach();      bool joinable() const noexcept;
id get_id() const noexcept;
static unsigned hardware_concurrency() noexcept;
Name Description
f, args... The callable and its arguments. Both are decayed-copied into storage owned by the new thread.
join() Blocks until the thread finishes. Afterwards joinable() is false.
detach() Releases the thread so it runs independently. You can no longer wait for it.
joinable() True if the object owns a thread that was not yet joined or detached.
get_id() A std::thread::id value that can be compared and streamed; the printed form is not specified.
std::this_thread::sleep_for(d), yield(), get_id() Functions that act on the calling thread.

Errors: the constructor can throw std::system_error if the thread cannot be created. join() and detach() throw if the thread is not joinable, or when joining itself (deadlock).

Usage notes

  • Exceptions do not cross threads. An exception that escapes the thread function calls std::terminate. Catch inside the function, or use std::async or a promise to carry the error back.
  • Pass by reference with std::ref, otherwise the function receives a copy, and a T& parameter will not compile.
  • Dangling references: a detached thread that uses locals of the creating function reads freed memory after that function returns. Join, or copy the data.
  • Move-only: std::thread cannot be copied. Store threads in a std::vector with emplace_back and join them in a loop.
  • Cost: creating a thread costs tens of microseconds and stack memory (often megabytes of address space). Reuse threads for many small tasks rather than starting one per task.
  • Prefer std::jthread in new code. It joins in its destructor and supports cooperative stopping.
  • Output from several threads interleaves unless guarded. The order in which threads run is not deterministic, so test with join, not with sleeps.
  • Count of cores: hardware_concurrency() is a hint and may return 0.