c++ - 阻止异步的解决方法?

标签 c++ c++11

下面的 async 调用正在阻塞,因为返回的 future 的析构函数正在阻塞:

void foo() {}

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

但我不想阻止!

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

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

这样好吗?或者您会推荐其他解决方案吗?

最佳答案

您可以使用以下版本的异步,它提供了一个非阻塞的 future 。因此,如果您需要,您可以利用 future ,另一方面,当您想要一个即发即弃的任务时,您可以忽略它。

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;   
}

关于c++ - 阻止异步的解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16296284/

相关文章:

c++ - 为什么 std::optional::value_or 没有默认构造函数类型的特化?

c++ - 为什么在使用堆叠 std::array 声明多维数组时需要 "double braces"?

c++ - 如果存储 unique_ptr,则不会构建 std::queue 的线程安全包装器,但 std::queue 可以工作

c++ - 使用用户定义的文字初始化 constexpr 数组

c++ - 为什么此 Boost.Spirit x3 规则使用尖括号正确解析,但使用引号解析错误?

c# - c++ exe如何定位c# dll?

c++ - 静态成员函数中静态变量的同名

c++ - Stroustrup 天鹅书 vector 问题

c++ - 有没有一种优雅的方法可以从 std::vector 实例化 boost::array?

c++ - 如何创建带参数的成员函数指针数组?