【发布时间】:2020-01-08 03:38:35
【问题描述】:
我有一个异步进程正在运行(使用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;
}
【问题讨论】:
-
让异步任务监控它使用的时间,如果超过时间限制则清理并退出返回默认值。没有干净的方法可以杀死线程。
-
如果你把等待逻辑放在
compute()函数中会怎样。执行快时返回一个值,否则返回另一个值(提前返回)。 -
@AlanBirtles 是否可以监视 main() 中的原子变量而不是线程本身?线程设置原子变量的状态。由于在线程级别高频检查原子状态会使架构复杂化。
-
想要...杀死它 你不能杀死一个线程。对不起。如果你想让它终止,你必须让它想要终止。
标签: c++ multithreading c++11 asynchronous