Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a program for a specified amount of time?

Tags:

c++

unix

For a computation intensive problem I want to limit the CPU time spent by the program: if the program doesn't find a solution within a given amount of time, I want the program to be terminated. Rather than having the program look for a solution forever, it should terminate if nothing is found. In case the platform matter, this is for UNIX. How can this be achieved?

like image 615
Dietmar Kühl Avatar asked Dec 10 '22 02:12

Dietmar Kühl


1 Answers

Another POSIX solution that's single-threaded and self-contained is to 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 very few legitimate and crucial uses of volatile: We must prevent the compiler from optimizing out the while (!done) conditional, and the compiler doesn't see that done can be mutated, because it's never touched inside the loop body.)

POSIX discourages the use of std::signal in favour of its own, more powerful sigaction. Consult the manual if you're interested, but for the simple purpose of raising an alarm this solution appears to suffice.

If your program offers no interruption points at all (i.e. points at which you can check done), then you could also call abort() in the signal handler.

like image 118
Kerrek SB Avatar answered Dec 11 '22 15:12

Kerrek SB