Can I time limit a function call?

Viewed 64

This is a problem I doubt has a solution meeting all of its constraints, but I may be - I hope I am - wrong.

Within a C++ - currently C++11 - program I have some code that we can assume to be a function call. Based on inputs before that call, that function might run in a time that is milliseconds, or could be up to and beyond any reasonable amount of time were it to be allowed to complete.

I would like to set a time limit on the length of time that function is allowed to run, after which it is stopped. In an ideal word it would be as if that function threw a specified exception, but any form of stopping, up to and including calling terminate() is acceptable.

It's not practical to modify the function, for various reasons, it has to be external to the function. Any solution allowed, as long as the features it uses are all standard C++ - as close to C++11 as possible but if needing to go later, OK. If the solution involves threads - that is not a requirement - those also would need to be cleaned up - including quickly if the function evaluates quickly (but need not be exactly at its time) and the function would need to stay in the main thread.

0 Answers
Related