我有一个函数,它可能执行非常慢的计算(请参见下面的基本示例)。该函数不会写入现有资源,没有副作用,并且仅对其所有变量使用自动分配(因此,在标准库中的任何调用之外,都不会调用new
和delete
)。
在运行了一定时间后是否有可能使该函数超时并释放其请求的堆内存,无修改该函数本身?
//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
}
不好的方法是在经过一段时间后在要终止的线程中运行该函数。
完全没有办法知道什么时候是安全的,以及当函数运行时如何修复程序的可修改状态。
一个函数可以分配资源,甚至是内部程序资源。为此,它需要修改全局数据结构,并且这些修改可能不是原子的,也不能被正确地撤消。
您需要一些合作。