c++ - 除了持续时间之外,是否有替代 std::this_thread::sleep_for 接收 std::stop_token 的替代方法?
问题描述
我想将std::this_thread::sleep_for和std::this_thread::sleep_until与std::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
}
}};
解决方案
使用 a std::condition_variable
,这涵盖了“有信号时停止”部分。然后你分别使用wait_for
或wait_until
。
可以在链接中找到有关如何使用条件变量的示例。