I have the following code to run a timed thread:
// Method to invoke a request with a timeout.
bool devices::server::CDeviceServer::invokeWithTimeout(CDeviceClientRequest& request,
CDeviceServerResponse& response)
{
// Retrieve the timeout from the device.
int timeout = getTimeout();
timeout += 500; // Add 500ms to cover invocation time.
// Invoke the request within a timed thread.
boost::promise<void> boostPromise;
boost::unique_future<void> boostFuture = boostPromise.get_future();
boost::thread boostThread([&]()
{
invoke(request, response);
boostPromise.set_value();
});
// The thread has timed out, if the future is not ready.
return (boostFuture.wait_for(boost::chrono::milliseconds(timeout))
==
boost::future_status::ready);
}
This appears to work without a problem, the function returns false when it times out.
However, then the code being invoked (by invoke(request, response);) throws an exception which kills the application. How do I successfully terminate the thread if it has not completed, and consume any exceptions.
I have tried the following:
// The thread has timed out, if the future is not ready.
bool completed = (boostFuture.wait_for(boost::chrono::milliseconds(timeout))
==
boost::future_status::ready);
if (!completed)
{
boostThread.interrupt();
}
return completed;
But this also throws an exception and crashes the application. I need a completely safe mechanism where the timed thread can be safely killed off, if the timeout has been reached.