包装返回诺言C ++

时间:2018-07-17 08:46:20

标签: c++ promise wrapper

我具有以下功能:

std::future<void> resolve_one() {
        typename std::list<matrix_wrap<T>>::iterator lhs = find_max();
        typename std::list<matrix_wrap<T>>::iterator rhs = lhs;
        ++rhs;
        typename std::list<matrix_wrap<T>>::iterator result=matrices.emplace(lhs,matrix<T>(lhs->get_height(),rhs->get_width()));

        auto lambda = [&]() {
            do_multiply(*result,*lhs,*rhs);
            matrices.erase(lhs);
            matrices.erase(rhs);
        };
        return std::async(std::launch::async, lambda);

    }

我的老师说我必须修改我写的包装器类,以便返回对do_multiply结果的承诺,因为我需要在(A + B)*(C + D)中进行并发操作, (A + B)和(C + D)在最终乘法之前异步执行。我完全不知道如何修改它,有人可以帮我吗?谢谢。您可以在这里找到我的包装器类:matrix_wrap

1 个答案:

答案 0 :(得分:0)

不要使用const input = [ 3, 1, 5, 4, 2 , 1, 3, 2, 5, 4 , 1, 4, 3, 5, 2 , 3, 2, 5, 1, 4 , 4, 1, 5, 2, 3 , 3, 2, 4, 5, 1 , 1, 5, 4, 2, 3 , 5, 2, 1, 4, 3 , 5, 3, 2, 4, 1 , 5, 3, 4, 1, 2]; const topLabels = "abcde"; const sideLabels = "zyxwvutsrq"; function labelForPos(p) { return { top: topLabels[p % 5], side: sideLabels[Math.trunc(p / 5)] } } const members = { 1: [], 2: [], 3: [], 4: [], 5: [] }; function check(sum, ixlist) { //make sure all are unique indexes if ((new Set(ixlist)).size !== ixlist.length) return; if (sum >= 1 && sum <= 5) { members[sum].push("[" + ixlist.map(ix => { const lb = labelForPos(ix); return `[${lb.side},${lb.top}]`; }).join(",") + "]" ); } } input.forEach((l0, l0ix) => { check(l0, [l0ix]); input.forEach((l1, l1ix) => { if (l1ix <= l0ix) return; check(l0 + l1, [l0ix, l1ix]); input.forEach((l2, l2ix) => { if (l2ix <= l1ix) return; check(l0 + l1 + l2, [l0ix, l1ix, l2ix]); }); }); }); Object.entries(members).forEach(([key, v]) => { console.log(`${key} (${v.length}) = [${v.join(", ")}]`); });来包装计算值。您应该尽可能对std::future<void>值进行操作。

std::future<matrix_wrapper<T>>

您将来可以使用using matrix_future = std::future<matrix_wrapper<T>>; matrix_future operator *(matrix_future lhs, matrix_future rhs) { return std::async(std::launch::async, [lhs=std::move(lhs), rhs=std::move(rhs)] mutable () { const auto & l = lhs.get(); const auto & r = rhs.get(); assert(l.get_width() == r.get_height()); matrix_wrap<T> result = *matricies.emplace(l.get_height(), r.get_width()); do_multiply(result, l, r); return result; }); } using matrix_future = std::future<matrix_wrapper<T>>; matrix_future operator +(matrix_future lhs, matrix_future rhs) { return std::async(std::launch::async, [lhs=std::move(lhs), rhs=std::move(rhs)] mutable () { const auto & l = lhs.get(); const auto & r = rhs.get(); assert(l.get_dims() == r.get_dims()); matrix_wrap<T> result = *matricies.emplace(l.get_dims()); do_add(result, l, r); return result; }); } (或std::promise(如果可用))轻松包装值

std::experimental::make_ready_future

然后像

一样使用
matrix_future make_ready_future(matrix_wrapper<T> mat)
{
     std::promise<matrix_wrapper<T>> prom;
     prom.set_value(std::move(mat));
     return prom.get_future();
}