阻止异步的解决方法? [英] Workaround for blocking async?

查看:138
本文介绍了阻止异步的解决方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的 async 调用是阻塞的,因为返回的未来的析构函数是阻塞的:

The async call below is blocking because the destructor of the returned future is blocking:

void foo() {}

void foo_async() {
    std::async(std::launch::async, foo);
}

但我不想阻止!

我正在考虑使用以下解决方法:

I'm considering to use the following workaround:

void foo_async() {
    std::thread(foo).detach();
}

这是否确定?

推荐答案

您可以使用以下版本的async来提供一个非阻塞的未来。因此,如果你需要它,你可以利用未来,另一方面,你可以忽略它,当你想要一个火和忘记的任务。

You could use the following version of async which provides a non-blocking future. As such you can take advantage of the future if you need it and on the other side you can just ignore it when you want a fire-and-forget task.

template< class Function, class... Args>
std::future<typename std::result_of<Function(Args...)>::type> async( Function&& f, Args&&... args ) 
{
    typedef typename std::result_of<Function(Args...)>::type R;
    auto bound_task = std::bind(std::forward<Function>(f), std::forward<Args>(args)...);
    std::packaged_task<R()> task(std::move(bound_task));
    auto ret = task.get_future();
    std::thread t(std::move(task));
    t.detach();
    return ret;   
}

这篇关于阻止异步的解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆