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.
source share