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.
#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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?