Skip to content

Instantly share code, notes, and snippets.

@bbolli
Created February 18, 2015 22:45
Show Gist options
  • Save bbolli/3a36ea809beb321e4d46 to your computer and use it in GitHub Desktop.
Save bbolli/3a36ea809beb321e4d46 to your computer and use it in GitHub Desktop.
A wrapper that runs a function with a timeout
// Needs to be compiled with -std=c++1y for optionals support
#include <chrono>
#include <cstdio>
#include <cstring>
#include <experimental/optional>
#include <future>
#include <type_traits>
// A shortcut to the result type of F(Args...).
template <typename F, typename... Args>
using result_t = typename std::result_of<
typename std::decay<F>::type(typename std::decay<Args>::type...)
>::type;
// A shortcut to the type of a duration D.
template <typename D>
using duration_t = std::chrono::duration<
typename D::rep, typename D::period
>;
// Run a function asynchronously if timeout is non-zero.
//
// The return value is an optional<result_t>.
// The optional is "empty" if the async execution timed out.
template <typename TO, typename F, typename... Args>
std::experimental::optional<result_t<F, Args...>>
with_timeout(const TO& timeout, F&& f, Args&&... args)
{
if (timeout == duration_t<TO>::zero())
return std::experimental::make_optional(f(args...));
std::printf("launching...\n");
auto future = std::async(std::launch::async,
std::forward<F>(f), std::forward<Args...>(args...));
auto status = future.wait_for(timeout);
std::printf("wait_for() is back\n");
if (status == std::future_status::ready)
return std::experimental::make_optional(future.get());
return std::experimental::optional<result_t<F, Args...>>();
}
int main()
{
const size_t SIZE = 100 * 1000 * 1000;
auto buf = new char[SIZE + 1];
std::memset(buf, 'a', SIZE);
buf[SIZE] = '\0';
// 10 ms is short enough to trigger the timeout sometimes on my i5-4570T CPU.
auto f = with_timeout(std::chrono::milliseconds(10), std::strlen, buf);
if (f)
std::printf("result = %zu\n", *f);
else
std::printf("timeout!\n");
delete[] buf;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment