std packaged task and std future

suggest change

std::packaged_task bundles a function and the associated promise for its return type:

template<typename F>
auto async_deferred(F&& func) -> std::future<decltype(func())>
{
    auto task   = std::packaged_task<decltype(func())()>(std::forward<F>(func));
    auto future = task.get_future();

    std::thread(std::move(task)).detach();

    return std::move(future);
}

The thread starts running immediately. We can either detach it, or join it at the end of the scope. The result is ready when the task function returns, not when the std::thread constructor returns. Detaching is unsafe if the callable uses objects whose lifetimes end before the task does.

Note that this is slightly different from std::async where the returned std::future when destructed will actually block until the thread is finished.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents