How to run the program for a certain time?

For an intensive computing task, I want to limit the processor time spent by the program: if the program does not find a solution in a given period of time, I want the program to be terminated. Instead of the program looking for a solution forever, it should stop if nothing is found. In the case of a platform, this is for UNIX. How can this be achieved?

+4
source share
2 answers

Another POSIX solution, which is single-threaded and self-contained, should use signals:

#include <unistd.h> #include <csignal> std::sig_atomic_t volatile done = 0; void game_over(int) { done = 1; } int main() { std::signal(SIGALRM, game_over); alarm(5); // this program will self-destruct in 5 seconds while (!done) { do_my_thing(); // or whatever; make sure this returns frequently } } 

(This is one of the few legitimate and important uses of volatile : we must prevent the compiler from optimizing the while (!done) condition, and the compiler does not see that done can be mutated because it never touched the loop body.)

POSIX prohibits the use of std::signal in favor of its own, more powerful sigaction . If you are interested, refer to the manual, but for the simple purpose of raising anxiety, this solution seems sufficient.

If your program does not have breakpoints at all (that is, points at which you can check done ), you can also call abort() in the signal handler.

+9
source

A possible approach is to set a process limit for the required time. UNIX constraints set with setrlimit() are observed by the runtime environment and they support both soft and hard limits. When a soft limit is reached, a signal is triggered, which can be used, for example. set a flag indicating that the program should terminate. When a hard limit is reached, the program should be terminated (although this does not seem to work on MacOS). Here is a simple sample program:

 #include <sys/resource.h> #include <iostream> #include <signal.h> sig_atomic_t finished = false; void limit(int) { finished = true; } int main() { signal(SIGXCPU, limit); struct rlimit limit; limit.rlim_cur = 2; limit.rlim_max = 3; setrlimit(RLIMIT_CPU, &limit); unsigned long long i(0); while (++i && !finished) { } std::cout << "i=" << i << " flag=" << std::boolalpha << bool(finished) << "\n"; } 
+5
source

Source: https://habr.com/ru/post/1395909/


All Articles