首页 > 解决方案 > 除了持续时间之外,是否有替代 std::this_thread::sleep_for 接收 std::stop_token 的替代方法?

问题描述

我想将std::this_thread::sleep_forstd::this_thread::sleep_untilstd::stop_token一起使用,如果在 std::stop_token 上请求停止(例如调用 jthread 破坏),则函数返回。我怎样才能做到这一点?

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

标签: c++multithreadingc++20

解决方案


使用 a std::condition_variable,这涵盖了“有信号时停止”部分。然后你分别使用wait_forwait_until

可以在链接中找到有关如何使用条件变量的示例。


推荐阅读