Question

I have been reading the boost thread documentation, and cannot find an example of what I need.

I need to run a method in a timed thread, and if it has not completed within a number of milliseconds, then raise a timeout error.

So I have a method called invokeWithTimeOut() that looks like this:

// 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 += 100; // Add 100ms to cover invocation time.

   // TODO: insert code here.

   // Invoke the request on the device.
   invoke(request, response);

   // Return success.
   return true;
}

I need to call invoke(request, response), and if it has not completed within timeout, the method needs to return false.

Can someone supple a quick boost::thread example of how to do this please.

Note: The timeout is in milliseconds. Both getTimeout() and invoke() are pure-virtual functions, that have been implemented on the device sub-classes.

Was it helpful?

Solution

Simplest solution: Launch invoke in a separate thread and use a future to indicate when invoke finishes:

boost::promise<void> p;
boost::future<void> f = p.get_future();
boost::thread t([&]() { invoke(request, response); p.set_value(); });
bool did_finish = (f.wait_for(boost::chrono::milliseconds(timeout)) == boost::future_status::ready)

did_finish will be true if and only if the invoke finished before the timeout.

The interesting question is what to do if that is not the case. You still need to shutdown the thread t gracefully, so you will need some mechanism to cancel the pending invoke and do a proper join before destroying the thread. While in theory you could simply detach the thread, that is a very bad idea in practice as you lose all means of interacting with the thread and could for example end up with hundreds of deadlocked threads without noticing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top