I would like to use std::this_thread::sleep_for and std::this_thread::sleep_until with std::stop_token where the functions return if stop is requested on std::stop_token (ex. jthread destruction is called). How can I achieve this?
std::jthread thread {[](std::stop_token stoken){
while(!stoken.stop_requested()) {
std::cout << "Still working..\n";
std::this_thread::sleep_for(5s); // use together with stoken
}
}};
Use a std::condition_variable
, this covers the 'stop when signalled' part. Then you use wait_for
or wait_until
respectively.
Examples on how to use a condition variable can be found at the links.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With