C++: How to implement a timeout for an arbitrary function call?

I need to call a library function that sometimes won't terminate within a given time, unfortunately. Is there a way to call the function but abort it if it doesn't terminate within n seconds?

I cannot modify the function, so I cannot put the abort condition into it directly. I have to add a timeout to the function externally.

Is it maybe a possible solution to start it as a (boost) thread, which I can then terminate after a certain time? Would something like that work? I actually believe the function is not thread-safe, but that wouldn't matter if I run it as the only single thread, right? Are there other (better) solutions?


You could spawn a boost::thread to call the API:

boost::thread api_caller(::api_function, arg1, arg2);
if (api_caller.timed_join(boost::posix_time::milliseconds(500)))
{
    // API call returned within 500ms
}
else
{
    // API call timed out
}

Boost doesn't allow you to kill the worker thread, though. In this example, it's just orphaned.

You'll have to be careful about what that API call does, because it may never release resources it's acquired.


I think the only safe way to accomplish this would be to spawn a separate sandbox process that calls the library function as a proxy to your application. You'll need to implement some type of IPC between your application and the proxy. Implementing a timeout on reading the IPC reply is then fairly trivial. If the read fails due to timeout, you can then safely terminate the proxy without risking the health of your application.


What you are talking about is typically called a "watchdog" system. The watchdog is typically a second thread which checks on the status of all the other threads. The watchdog typically is setup to run periodically. If no response has been received from the other threads, the watchdog can notify the user, or even kill the offending thread if its possible to do so safely (depends on your application).