之后如何为 std::async 修改 std::launch 政策?

How can I modify the std::launch policy afterwards for std::async?

假设我想在我的 C++ 代码中使用 std::async 与 运行 计算量大的函数 func 并行。现在因为它是一个繁重的功能,我们可能首先使用 std::launch::deferred 政策,因为情况是我们可能根本不需要 运行。

但是如果以后我们需要突然执行它们,我们希望并行运行。那以后怎么修改std::launch策略呢

[嗯,可以说你为什么不 突然 创建 std::asyncs 作为 突然 你需要执行。但我在这里假设我不能那样做。]

或者,除了使用 std::async 之外,还有更好更简洁的方法吗?

非常感谢任何帮助。提前致谢。

#include <future>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <iostream>

std::vector<double> func(size_t n) // a computationally heavy function
{
    std::vector<double> vec(n);
    std::generate_n(vec.begin(), n, std::rand);
    return vec;
}

int main()
{
    // create asyncs, now deferred for lazy execution
    auto v1 = std::async(std::launch::deferred, func, 200); // deferred for lazy execution
    auto v2 = std::async(std::launch::deferred, func, 250); // deferred for lazy execution

    // only after sometime we decide to execute both of them
    // but we also now want them to execute in parallel

    // so how can we now change the launch policy?

    // to get the values as quickly as can be
    auto n1 = v1.get().size();
    auto n2 = v2.get().size();

    std::cout<<"Got "<<n1<<" and "<<n2<<" random numbers in parallel!"<<std::endl;
    return 0;
}

更新

多想一点导致我遇到这个问题:

std::launch::deferred定义std::async后,调用.get()函数时,是否会保证到运行 async(即并行)当然不是。 http://en.cppreference.com/w/cpp/thread/launch

it is executed on the calling thread.

然后 async 的概念就被破坏了,对吧?

如果std::async使用std::launch::deferred那么当调用返回的std::future对象的get()函数时是运行。

这表明您可以像这样强制 std::launch::async

int s1 = 0;
int s2 = 0;

auto v1 = std::async(std::launch::deferred, []{ return 1; });
auto v2 = std::async(std::launch::deferred, []{ return 2; });

// some fancy coding ...

if(need_to_upgrade_launch_policy())
{
    auto v1a = std::async(std::launch::async, [&]{ return v1.get(); });
    auto v2a = std::async(std::launch::async, [&]{ return v2.get(); });

    s1 = v1a.get();
    s2 = v2a.get();
}

//  more clever coding ...

if(v1.valid()) // was never upgraded
    s1 = v1.get();

if(v2.valid()) // was never upgraded
    s2 = v2.get();