jthread 的 std::this_thread 在哪里?

Where is std::this_thread for jthread?

无法弄清楚 jthreadstd::this_thread 在哪里?

我有一个函数,理论上可以让 jthread 休眠直到请求取消:

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

如何在 jthread 上调用它?

理论上下面的程序会在 1 秒内退出:

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.

这是一个例子:

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();

生活在 Godbolt