2

我有一个异步进程正在运行(使用std::async),我想测量执行时间并在执行时间过长时终止它。此过程在执行后还会返回一个值,如果计算时间过长,我想分配一些默认值作为结果。任何帮助/建议将不胜感激!

#include <thread>
#include <future>

int compute(int val)
{
    int result;

    // do large computations

    return result;
}
void main()
{
    auto compute_thread = std::async(compute, 100);

    // TODO: wait for result only for x milliseconds else assign some default value
    int result = compute_thread.get();

    // resume sequential code.
    int final = result * 2;
}
4

2 回答 2

0

这是我的想法的样子(参见内联代码注释):

// Performs computations and exits when computation takes
// longer than maxTime. If the execution is timed out
// function returns valueIfTooLong.
// If the computation complete the function returns 0.
static int compute(int maxTime /*ms*/, int valueIfTooLong)
{
  auto start = std::chrono::steady_clock::now();
  for (short i = 0; i < std::numeric_limits<short>::max(); ++i)
  {
    auto now = std::chrono::steady_clock::now();
    if (std::chrono::duration_cast<std::chrono::milliseconds>(now - start).count() > maxTime)
    {
      return valueIfTooLong;
    }
  }

  return 0;
}

函数的用法:

int main()
{
  const auto valueIfTooLong = 111;
  const auto waitingTime = 10; // ms.
  auto compute_thread = std::async(std::launch::async, compute, waitingTime, valueIfTooLong);

  // Wait for result only for waitingTime milliseconds else assign valueIfTooLong
  int result = compute_thread.get();
  if (result == valueIfTooLong)
  {
    std::cout << "The calculation was longer than "
              << waitingTime << "ms. and has been terminated" << '\n';
  }
  else
  {
    std::cout << "The calculation is done" << '\n';
  }

  return 0;
}
于 2019-09-05T12:35:29.627 回答
-2

您可以使用

std::future<int> compute_thread;
void main()
{
    auto timeToWait = std::chrono::system_clock::now() + std::chrono::minutes(1); // wait for a minute
    compute_thread = std::async(compute, 100);

    // TODO: wait for result only for x milliseconds else assign some default value
    std::future_status status = compute_thread.wait_until(timeToWait);

    if(status == std::future_status::ready)
        int final = compute_thread.get() * 2;
    else
        // you need another value based on what you're doing
}

注意:如果您的异步是一个长时间的计算,您可能有另一个函数计算相同的东西但不太准确......在这种情况下,同步任务不会被杀死。你只等待完成(如果及时),如果结果还没有准备好,你继续做你的工作......这是一种不被阻止的方法compute_thread.wait()

注意 2:std::future<int> compute_thread被声明为全局,因为如果你在函数中(而不是在 main 中)执行此操作,则必须确保 compute_thread 的生命周期比函数生命周期长。

于 2019-09-05T09:37:57.403 回答