Concurrency with std::thread
Prerequisites: Ranges (C++20)
std::thread (C++11) wraps the platform's native threading, giving
a portable, RAII-friendly API — replacing the raw pthread calls
used in Learn C's advanced lessons:
#include <thread>
void printNumbers() {
for (int i = 0; i < 3; i++) {
std::cout << "Thread: " << i << std::endl;
}
}
int main() {
std::thread t(printNumbers);
t.join(); // wait for it to finish
return 0;
}
Common mistakes
- Letting a
std::threadobject be destroyed while stilljoinable()(neither.join()ed nor.detach()ed) — this callsstd::terminate, crashing the program immediately.