std :: async变体,适用于集合

时间:2012-06-05 17:45:18

标签: c++ concurrency c++11 future

使用std::async我想知道是否有可能有一个辅助函数,它可以从集合中创建std::future(每个集合元素都有一个未来)。

我经常遇到以下情况:

auto func = []( decltype(collection)::reference value ) {
  //Some async work
};

typedef std::result_of<decltype(func)>::type ResultType;
std::vector<std::future<ResultType>> futures;
futures.reserve(collection.size());

// Create all futures
for( auto& element : collection ) {
  futures.push_back(std::async(func, element));
}

// Wait till futures are done
for( auto& future : futures ) {
  future.wait();
}

为了能够轻松地重复使用,我提出了以下部分代码:

template< class Function, class CT, class... Args>
std::vector<std::future<typename std::result_of<Function(Args...)>::type>>
async_all( Function&& f, CT& col ) {

    typedef typename std::result_of<Function(Args...)>::type ResultType;
    std::vector<std::future<ResultType>> futures;
    futures.reserve(collection.size());

    for( auto& element : collection ) {
        futures.push_back(std::async(func, element));
    }
}
return futures;

现在我必须解决Args问题,因为在async_all中,Args无法再推断出来。我目前唯一能想到的是另一个仿函数,它将集合中的元素转换为Args。 有没有更优雅的解决方案?

1 个答案:

答案 0 :(得分:3)

你快到了。传递给async_all的集合具有我们唯一确定函数参数类型所需的所有信息;唯一的问题是如何提取这些信息。使用函数签名中的auto关键字,我们可以在函数参数之后编写返回类型。这不仅可以生成更清晰的签名,还可以让我们在推导返回类型时将参数值与decltype一起使用。例如:

template<typename F, typename CT>
auto reduce(F f, CT coll) -> decltype(f(*begin(coll), *begin(coll));

当然,还有其他方法可以确定所提供函数的参数类型(使用带模板的函数签名推导)。但是,对于涉及重载函数和/或模板化函数对象的情况,这些方法可能会失败。

以下代码在gcc 4.8下编译并正常运行(打印“x = 1”10次)(早期版本应该可以正常工作)。请注意我们甚至不必明确提及std::future:我们可以直接在std::async语句中使用decltype来推断它的类型。

#include <future>
#include <vector>
#include <iostream>

template<class Function, class CT>
auto async_all(Function f, CT col)
    -> std::vector<decltype(std::async(f, *std::begin(col)))>
{
    std::vector<decltype(std::async(f, *std::begin(col)))> futures;
    futures.reserve(col.size());

    for (auto& element : col) {
        futures.push_back(std::async(f, element));
    }
    return futures;
}

int main()
{
    using namespace std;
    for (auto& f : async_all([](int x) { cout << "x = " << x << endl; }, 
                             vector<int>(10, 1)))
       f.get();
}

async_all在这里仅评估一次,因为规范保证了基于范围的for循环中的范围表达式)

相关问题