c++ - 自动终止 C++11 STL 线程

标签 c++ c++11

我希望 STL 线程在完成它应该做的事情后自行终止;另外,有什么方法可以知道线程何时结束?比如某个事件。

提前致谢。

最佳答案

如果您想要一种方法来轮询线程的完成状态,而不是简单地使用 join 进行阻塞, 你可以用 async 产生你的线程并轮询返回的 futurewaiting 完成超时为 0:

void f() {
  std::this_thread::sleep_for(std::chrono::seconds{2});
}

int main() {
  auto const zero = std::chrono::seconds{0};
  auto result = std::async(std::launch::async, f);
  while (result.wait_for(zero) != std::future_status::ready) {
    std::cout << "I'm still waiting...\n" << std::flush;
    std::this_thread::sleep_for(std::chrono::milliseconds{100});
  }
  result.get();
  std::cout << "Done.\n";
}

关于c++ - 自动终止 C++11 STL 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21664360/

相关文章:

c++ - 如果需要,如何使用 Boost 库将具有可变数量参数的处理程序传递给类

localtime_r 的 C++11 替代方案

c++ - 与类一起使用时,std::reference_wrapper "has no member named"编译错误

c++ - 如何静态检查模板的类型 T 是否为 std::vector<U>,其中 U 为 float、double 或 integral

c++ - 在 C++11 环境中使用 VLA

c++ - 这是使用 union vs reinterpret_cast 的合适案例吗

c++ - 映射键排序

c++ - 在这种情况下使用 std::vector 的哪个构造函数

c++ - 如何使策略决定成员变量类型?

c++ - 如何处理 std::find_if() 返回 false?