异步控制线程执行时间
Control thread execution time in async
我有一个异步进程正在运行(使用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的寿命比函数寿命长。
相关文章:
- 我使用 OpenMP 的线程越多,执行时间就越长,这是怎么回事?
- 将进程的执行从线程1转移到线程2
- 使用 4 个和 8 个线程运行时执行的时间相等
- 我们是否需要互斥锁来执行多线程文件 IO
- OpenMP 并行编程基于线程数与执行时间的关系
- 使用OpenMP库,执行时间如何取决于线程数量的增加
- OpenMP 一次只执行一个线程
- 线程:如何在C或C++中精确计算算法的执行时间(函数的持续时间)
- 具有随机数总和的多线程执行时间
- C++和OpenMP——线程的执行时间大不相同
- 如何使生成的线程拖延足够长的时间以使生成线程执行某些操作
- 使用多线程优化执行时间(简单示例)
- 为什么一个子线程的执行时间多于整个应用程序的执行时间
- 获取c++ Builder中执行进程/线程的ID
- 在执行多线程处理时保存数据
- 在C++中执行跨平台线程间通知的好方法是什么?
- 如何度量一个线程的执行时间?
- 线程的执行时间改变
- 多线程环境下的执行时间
- C++ 线程执行时间和另一个线程中的执行线程