dimanche 25 mars 2018

Exit a function if it doesn't terminate after a certain amount of time

Say I have a function whose prototype looks like this:

std::vector<int> func(int param);

The function may or may not cause an infinite loop; it is impossible to tell which inputs will cause a successful termination and which will cause an infinite loop.

Therefore, I need a way to terminate the function if it doesn't finish after, say 1000 ms.

I've tried using std::async to isolate the function, but I can't figure out how to time the thread or forcibly terminate it:

auto future = std::async(func, param);
std::vector<int> result = future.get();

Another solution that I've considered is an internal global timer that is updated from within the function and checked regularly; if a certain amount of time has elapsed, then the function will forcibly return. However, I would rather not modify the function itself, and instead have everything be external.

How can I perform this?

Aucun commentaire:

Enregistrer un commentaire