On this page
std::thread
Prev: std::mutex & std::scoped_lock | Up: concurrency | Next: std::atomic
Rel: std::jthread
Ref: cppreference — std::thread
Tags: #public #prog #cpp #stdlib #concurrency #tier/standard
Overview
std::thread (<thread>, C++11) wraps an OS thread of execution. Unlike std::jthread, if a joinable std::thread is destroyed without calling join() or detach(), the C++ runtime immediately invokes std::terminate().
Notes & Pitfalls
- Destroying a joinable
std::threadcallsstd::terminate(): Always.join()or.detach()before destruction, or preferstd::jthread(C++20). - Wrap reference arguments in
std::ref(x):std::threadcopies arguments by value by default.
Example
#include <cassert>
#include <functional>
#include <thread>
int main() {
int result = 0;
std::thread t([](int& out) { out = 99; }, std::ref(result));
t.join();
assert(result == 99);
}
Linked from
Related notes
- tuts/cpp/stdlib/concurrency/atomic Linked here; links to this page; shared tags: #concurrency, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/jthread Linked here; links to this page; shared tags: #concurrency, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/mutex_and_lock_guard Linked here; links to this page; shared tags: #concurrency, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency Linked here; links to this page; shared tags: #concurrency, #cpp, #prog, #stdlib
- tuts/cpp/stdlib/algorithm_and_ranges/find_if shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/ranges_views shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/sort shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/transform shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/array shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/expected shared tags: #cpp, #prog, #stdlib, #tier