C++中类似于context-select的特性是什么?

6

想象一下这样一种情况,我希望调用一个进行一些处理但时间限制的函数。 我可以使用Go语言中的和

1个回答

6

也许可以这样说:

void longRunning(std::atomic<bool>& stop) {
  for (;;) {
    if (stop) return;
    // Do a bit of work
  }
}

int main() {
  std::atomic<bool> stop = false;
  auto future = std::async(std::launch::async, longRunning, std::ref(stop));
  future.wait_for(std::chrono::seconds(num_seconds));
  stop = true;
  future.get();  // wait for the task to finish or exit early.
}

演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接