Timeout if a thread doesn't return within a specified period

Viewed 20

I would like to execute a lambda function asynchronously in MSVC C++. But if the function doesn't return the result within the specified duration, then the caller should just return with a timeout flag, leaving the thread detached so that it can later exit in a clean memory safe way.

I was able to somewhat achieve this using std::async and std::future, but my implementation is somehow leaking memory due to some bug. How to achieve the same behavior using std::thread + detach semantics?

 auto f = std::make_shared<std::future<T>>();
 *f = std::async(std::launch::async, [f, fun]() { return fun(); });

 auto status = f->wait_for(timeoutInSeconds);

 if (status == std::future_status::timeout)
 {
    return std::make_tuple(false, T{});
 }

 return std::make_tuple(true, f->get());

0 Answers
Related