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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With