我有以下代码来运行定时线程:
// 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);
}
这似乎没有问题,该函数在超时时返回 false。
然而,被调用的代码(通过invoke(request, response);)会抛出一个异常,从而杀死应用程序。如果线程尚未完成,我如何成功终止线程并处理任何异常。
我尝试了以下方法:
// 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;
但这也会引发异常并使应用程序崩溃。我需要一个完全安全的机制,如果达到超时,可以安全地关闭定时线程。