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?
Share
Another POSIX solution that’s single-threaded and self-contained is to use signals:
(This is one of the very few legitimate and crucial uses of
volatile: We must prevent the compiler from optimizing out thewhile (!done)conditional, and the compiler doesn’t see thatdonecan be mutated, because it’s never touched inside the loop body.)POSIX discourages the use of
std::signalin favour of its own, more powerfulsigaction. 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 callabort()in the signal handler.