简体   繁体   中英

Where is std::this_thread for jthread?

Can't figure out where is std::this_thread for jthread ?

I have a function that theoretically makes a jthread sleep until a cancellation is requested:

template<typename Rep, typename Period>
void sleep_for(const std::chrono::duration<Rep, Period>& d, const std::stop_token& token)
{
    std::condition_variable cv;

    std::mutex mutex;

    std::unique_lock<std::mutex> lock{ mutex };

    std::stop_callback stop_wait{ token, [&cv]()
    {
        cv.notify_one(); }
    };

    cv.wait_for(lock, d, [&token]()
    {
        return token.stop_requested();
    });
}

How do I call it on jthread ?

Theoretically the program below exits within 1 second:

int main()
{
    std::jthread t([]()
    {
        //where do I get `stop_token`?
        sleep_for(std::chrono::seconds(5), std::this_jthread::get_stop_token());
    });

    std::this_thread::sleep_for(std::chrono::seconds(1));

    t.request_stop();

    return 0;
}

The jthread constructor accepts a function that takes a std::stop_token as its first argument, which will be passed in by the jthread from its internal stop_source.

Here is an example:

std::jthread t([](std::stop_token stop_token)
{
    while(!stop_token.stop_requested()) {
        //Process data...
        std::this_thread::sleep_for(std::chrono::seconds(5));
    }   
});
std::this_thread::sleep_for(std::chrono::seconds(1));
t.request_stop();

live on Godbolt .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM