gpt4 book ai didi

c++ - 默认启动策略和 std::launch::deferred 之间的区别

转载 作者:行者123 更新时间:2023-11-30 05:35:18 26 4
gpt4 key购买 nike

我写了一些代码来诊断默认启动策略和 std::launch::deferred 之间的区别。

#include <chrono>
#include <vector>
#include <future>
#include <thread>
#include <iostream>

int main() {

auto func = [] {
std::cout << std::this_thread::get_id() << "," << std::flush;
int i=std::numeric_limits<int>::max();
while(i--);
std::cout << "b" << std::flush;
};

std::vector<std::future<void> > vec;
for (int i = 0; i < 10; ++i) {
vec.push_back(std::async( std::launch::deferred, func ));
}
for (auto &t : vec) {
t.get();
}

}

以上代码的输出是:

140257438672704,b140257438672704,b140257438672704,b140257438672704,b140257438672704,b140257438672704,b140257438672704,b140257438672704,b140257438672704,b140257438672704,b

#include <chrono>
#include <vector>
#include <future>
#include <thread>
#include <iostream>

int main() {

auto func = [] {
std::cout << std::this_thread::get_id() << "," << std::flush;
int i=std::numeric_limits<int>::max();
while(i--);
std::cout << "b" << std::flush;
};

std::vector<std::future<void> > vec;
for (int i = 0; i < 10; ++i) {
vec.push_back(std::async( func ));
}
for (auto &t : vec) {
t.get();
}

}

以上代码的输出是:

140200948524864,b140200948524864,b140200948524864,b140200948524864,b140200948524864,b140200948524864,b140200948524864,b140200948524864,b140200948524864,b140200948524864,b

它仍然在主线程上运行任务。我的问题是为什么在使用默认启动策略(我的机器有 4 个内核)时它不安排更多线程运行得更快?

最佳答案

根据 cppreference.com当您没有明确通过政策时:

1) Behaves the same as async(std::launch::async | std::launch::deferred, f, args...). In other words, f may be executed in another thread or it may be run synchronously when the resulting std::future is queried for a value.

当两个标志都启用时:

If both the std::launch::async and std::launch::deferred flags are set in policy, it is up to the implementation whether to perform asynchronous execution or lazy evaluation.

因此,区别在于默认情况下,策略是延迟启动或异步启动。选择取决于实现。 policy延期了,lauch就只能延期了。

My question is why it doesn't schedule more thread to run faster when using default launch policy(my machine got 4 cores)?

这不是必需的,并且实现选择不这样做。

关于c++ - 默认启动策略和 std::launch::deferred 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33936153/

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