Module lessons (3/4)
Threads in C++: std::thread and std::jthread (C++20)
Initiate concurrent executions, join/detach, safe argument passing, and RAII auto-join with std::jthread.
What you'll learn in this lesson
- Start parallel executions by passing functions or lambdas to
std::thread(<thread>). - Understand the critical rule of
join()(avoidingstd::terminatedestroying a still joinable thread). - Simplify thread management with automatic RAII and cooperative deletion of
std::jthread(C++20).
Overview
Since C++11 concurrency has been part of the standard (<thread>). A std::thread object represents a single independent flow of execution of the operating system on the same memory space as the process.
Pass a function or lambda to the constructor of std::thread. Before the object t goes out of scope, you must call t.join() to wait for it to finish (or t.detach(), not recommended for uncontrolled life):
Sections covered in this lesson
- 11. Start and Wait for
std::threadwith.join() - 22. Danger of
std::threadNon-United (std::terminate) - 33. C++20
std::jthread: Auto-Join RAII +std::stop_token - 44. Pass References to
std::thread(std::ref) - 5Practical exercises
- 6Check for understanding
Unlock "Threads in C++: std::thread and std::jthread (C++20)" and the full Course C++ curriculum
Initiate concurrent executions, join/detach, safe argument passing, and RAII auto-join with std::jthread.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course C++ plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.