Article by Ayman Alheraki on January 11 2026 10:36 AM
C++23 introduced a set of new features to improve multithreading in C++, making writing concurrent programs safer and easier. Here are some of the most prominent additions:
std::jthread: This is an improvement over the standard std::thread type. It automatically joins the thread when it goes out of scope, preventing resource leaks. It also provides an easy way to safely stop the thread using a stop_token.
std::barrier: This allows a group of threads to synchronize at a specific point in the program. All threads wait at the barrier until a predetermined number of threads reach the barrier, then all resume at the same time.
std::latch: This is similar to std::barrier, but it allows reaching the synchronization point only once. Once the required number of threads arrive, the latch is opened and cannot be reset.
std::atomic_ref<T>: This provides thread-safe access to non-atomic objects, allowing atomic operations on regular variables.
std::mdspan: This introduces a flexible and high-performance way to represent multidimensional arrays, with good support for parallel execution.
These new features significantly enhance the multithreading capabilities in C++, making it easier for developers to write efficient and safe concurrent programs.
Simple example using std::jthread:
void do_work(std::stop_token stop_token) { while (!stop_token.stop_requested()) { std::cout << "Working...\n"; std::this_thread::sleep_for(std::chrono::seconds(1)); } std::cout << "Stopping...\n";}
int main() { std::jthread worker(do_work); std::this_thread::sleep_for(std::chrono::seconds(5)); worker.request_stop(); // Requests the thread to stop safely // No need for worker.join() here, joining is done automatically when worker goes out of scope return 0;}
In this example, the worker thread performs a specific task until it's requested to stop using request_stop(). Thanks to std::jthread, there's no need to worry about manually joining the thread, making the code safer and easier to read.