gpt4 book ai didi

C++:函数外的超时函数

转载 作者:行者123 更新时间:2023-12-02 10:21:54 24 4
gpt4 key购买 nike

我有一个执行可能非常慢的计算的函数(参见下面的基本示例)。该函数不写入现有资源,没有副作用,并且只对其所有变量使用自动分配(因此,newdelete 永远不会被调用,在标准库中的任何调用之外)。

是否可以在函数运行一定时间后使函数超时并释放它所请求的堆内存,而不修改函数本身?

//Returns all primes up to n (fairly bad implementation; the idea is that it runs too long)
std::vector<int> primes(int n) {
std::vector<int> list={2};
for (int i = 3; i <= n; i++) {
bool flag= 0;
for (const auto& j : list) {
if (i % j == 0) {
flag= 1;
break;
}
}
if (!flag)
list.push_back(i);
}
return list;
}

main看起来像这样:
int main(){
std::vector<std::vector<int>> list_of_lists(6);
#pragma omp parallel for num_threads(6)
for (int n = 1; n < 7; n++) {
//I want the assignment below to make list_of_lists[n-1] empty if it takes more than 5 secs
list_of_lists[n-1] = primes(n*100000);
}
//use the list_of_lists
}

函数 primes本身不得修改。

有一种方法可以使用 std::async从函数外部检查耗时,但不幸的是没有办法杀死 std::future在它完成之前。所以我想知道最好的方法是什么。

最佳答案

如果没有注意到功能,任何形式的“终止”都是有风险的。
您可以做的最好的事情是有一个循环,它定期检查函数外部可见的“终止”标志并退出,或者测量函数内耗时。

for(;;)
{
if (bExit)
break;

// calculations here
}

不好的方法是在经过一段时间后终止的线程内运行函数。

关于C++:函数外的超时函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59803838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com