Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::thread — starting a thread and managing its lifetime

std::thread runs a callable in a separate thread. Learn how joinable(), join(), and detach() differ, and why the association with a thread must be resolved before its object is destroyed.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <thread>
std::thread t(callable);
bool active = t.joinable();
t.join();
// Alternative to join(): t.detach();

std::thread from <thread> represents one thread of execution; its callable-taking constructor runs that callable in a new thread. The object is movable but not copyable. Default construction starts no thread. This entry covers API used in C++23; the supplied source is an evolving working draft, not a frozen C++23 publication.

std::thread::joinable() tests whether the object still represents a thread, not whether that thread is still running. A finished thread remains joinable until a successful join() or detach(). std::thread::join() waits for completion and synchronizes that completion with its successful return. Consequently, the example can read result after join() without an additional mutex.

std::thread::detach() removes the object's association with the thread without waiting for the work to finish. It neither stops the thread nor extends captured objects' lifetimes: references to local variables can become dangling. After a successful join() or detach(), joinable() returns false.

Destroying a joinable object calls std::terminate(), even if its work has already finished. Arrange lifetime handling on exception paths too; an exception escaping the thread's callable also calls std::terminate(). join() and detach() can throw std::system_error; do not call them on a non-joinable object or call join() from the represented thread. Operations on the same std::thread object are not automatically synchronized.

Examples

#include <iostream>
#include <thread>

int main() {
    int result = 0;
    std::thread worker([&result] { result = 42; });
    const bool before = worker.joinable();
    worker.join();
    std::cout << std::boolalpha
              << before << '\n'
              << worker.joinable() << '\n'
              << result << '\n';
}

Result

true
false
42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources