【问题标题】:Is there an alternative to std::this_thread::sleep_for that receives std::stop_token besides time duration?除了持续时间之外,是否有替代 std::this_thread::sleep_for 接收 std::stop_token 的替代方法?
【发布时间】:2021-09-06 18:01:55
【问题描述】:

我想将 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++ multithreading c++20


【解决方案1】:

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

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

【讨论】:

  • 我不确定条件变量是否是我想要的
  • @asmbaty 要取消线程的休眠,我可以想象的方式并不多(符合 C++ 标准)。从一开始就告诉它,等待一段时间某个条件是一种干净的方式。因此,我想知道您为什么对 condition_variable 有疑问...
  • @asmbaty 我很确定这就是你想要的。 :-)
  • @asmbaty 但这正是 STL 为您所描述的此类用例所预见的。如果您不喜欢这样,您可能必须完全自己编写解决方案——很可能依赖于特定于操作系统的功能来避免忙等待(请这样做!)。
  • std::condition_variable_any::wait_for 自 C++20 以来有一个重载,它接收 std::stop_token 作为参数。
【解决方案2】:

这是我使用 std::condition_variable 的实现,正如大家所说的那样。

template<typename _Rep, typename _Period>
void sleep_for(const std::chrono::duration<_Rep, _Period>& dur, const std::stop_token& stoken)
{
    std::condition_variable 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(); });
}

【讨论】:

  • 这将导致问题提及here,因此您需要使用std::condition_variable_any。无论如何,这给了我解决问题的方向,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-25
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
  • 2013-04-25
  • 1970-01-01
  • 2021-12-25
相关资源
最近更新 更多