异步控制线程执行时间

Control thread execution time in async

本文关键字:执行时间 线程 异步控制      更新时间:2023-10-16

我有一个异步进程正在运行(使用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;
}

以下是我的想法(请参阅内联代码注释(:

// 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;
}

您可以使用

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的寿命比函数寿命长。