I have a function that performs a potentially very slow calculation (see below for a basic example). The function does not write to existing resources, there are no side effects, and only uses automatic allocation for all its variables (so new
and delete
are never called, outside of any calls within the standard library).
Is it possible to time-out the function after it's been running for a certain amount of time and free the heap memory it has requested, without modifying the function itself?
//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;
}
And main
looks like this:
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
}
The function primes
itself must not be modified.
There is a way to use std::async
to check for the time elapsed from outside the function, but unfortunately there is no way to kill a std::future
before it finishes. So I am wondering what's the best way to do this.