How do I use std::jthread and stop_token?

The `std::jthread` is a feature introduced in C++20 that simplifies thread management by automatically joining when the thread object goes out of scope. Additionally, it supports `std::stop_token`, providing a way to signal threads to stop gracefully. This is especially useful for managing thread lifetimes and ensuring proper resource cleanup.

Example of using std::jthread and stop_token

#include <iostream> #include <thread> #include <stop_token> #include <chrono> void threadFunction(std::stop_token st) { while (!st.stop_requested()) { std::cout << "Thread is running..." << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(500)); } std::cout << "Thread is stopping..." << std::endl; } int main() { std::jthread t(threadFunction); // Automatically joins at the end of main std::this_thread::sleep_for(std::chrono::seconds(2)); t.request_stop(); // Request the thread to stop return 0; }

C++ jthread stop_token multithreading C++20