Reputation: 516
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
}
}};
Upvotes: 3
Views: 1353
Reputation: 516
Here is my implementation using std::condition_variable as everyone tells that.
template<typename _Rep, typename _Period>
void sleep_for(const std::chrono::duration<_Rep, _Period>& dur, const std::stop_token& stoken)
{
std::condition_variable_any cv;
std::mutex mutex_;
std::unique_lock<std::mutex> ul_ {mutex_};
std::stop_callback stop_wait {stoken, [&cv](){ cv.notify_one(); }};
cv.wait_for(ul_, dur, [&stoken](){ return stoken.stop_requested(); });
}
Upvotes: 4
Reputation: 25536
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.
Upvotes: 8