Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an alternative to std::this_thread::sleep_for that receives std::stop_token besides time duration?

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
    }
}};
like image 741
asmbaty Avatar asked Sep 01 '25 04:09

asmbaty


1 Answers

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.

like image 138
Aconcagua Avatar answered Sep 02 '25 17:09

Aconcagua