gpt4 book ai didi

c++ - 之后如何为 std::async 修改 std::launch 策略?

转载 作者:太空狗 更新时间:2023-10-29 22:57:35 25 4
gpt4 key购买 nike

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

但如果将来我们需要突然执行它们,我们希望并行运行。那么之后我们如何修改std::launch策略。

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

或者,除了使用 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();

关于c++ - 之后如何为 std::async 修改 std::launch 策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43574372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com