asmbaty
asmbaty

Reputation: 516

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
    }
}};

Upvotes: 3

Views: 1353

Answers (2)

asmbaty
asmbaty

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

Aconcagua
Aconcagua

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

Related Questions