为什么我用异步获取future_error?

时间:2018-04-08 17:50:35

标签: c++11 asynchronous visual-c++ future

我需要并行开始执行任务向量并等到完成。这是我如何做到这一点,但我得到了MSVC的future_error。将矢量分成若干部分的小实用程序:

template<typename T>
vector<vector<T>> split(const vector<T>& vec, size_t n) {
    vector<vector<T>> outVec;
    size_t length = vec.size() / n;
    size_t remain = vec.size() % n;
    size_t begin = 0;
    size_t end = 0;
    for (size_t i = 0; i < std::min(n, vec.size()); ++i) {
        end += (remain > 0) ? (length + !!(remain--)) : length;
        outVec.push_back(std::vector<T>(vec.begin() + begin, vec.begin() + end));
        begin = end;
    }
    return outVec;
};

启动异步执行:

template <typename T, typename R, typename F>
void execInParallel(vector<T> &tasks, vector<R> &res, F&&f, int cores) {
    function<int(int &t)> fn(std::forward<F>(f));
    auto parts = split(tasks, cores);
    vector<future<vector<R>>*> threads;
    for (auto part: parts) {
        future<vector<R>> thrd=async(launch::async, [&](vector<T> tasks) {
            vector<R> rs;
            for (auto&t : tasks) {
                rs.push_back(fn(t));
            }
            return rs;
        }, part);
        threads.push_back(&thrd);       
    }
    for (auto&thrd : threads) {
        vector<R> rs = thrd->get();
        for (auto &r : rs)
            res.push_back(r);
    }
};

测试愚蠢的例子:

int main(){
    vector<int> tasks,res;
    tasks.push_back(1);
    tasks.push_back(7);
    tasks.push_back(19);
    execInParallel(tasks,res, [&](int&t) {
        return t+8;
    }, 2);
    return 0;
}

可能是我在发明一辆自行车?在C ++ 11中是否有类似的东西或开箱即用?有任何可用的例子吗?

0 个答案:

没有答案