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

标签 c++ multithreading c++11 asynchronous std

我写了一些代码来诊断默认启动策略和 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/

相关文章:

c++ - 在使用 libstdc++ 进行调试期间强制在 std::atomic 中使用锁

java - 使用 copyFromRealm 发送副本时从不正确的线程异常访问 Realm

C++ : elegantly iterate a set of numbers

c++ - 内联初始化静态常量类成员的初始化顺序保证

c++ - boost 共享指针 C++ : shared pointer unable to free resource on release

c++ - 如何使用 CMake 链接到 Capstone?

c++ - 基于 32 位和 64 位系统的 C 或 C++ 语言的数据类型大小有何不同

java - 在 Java 中等待多个线程完成

c++ - 使用 C++11/14 正确定义 DLL 接口(interface)

c++ - 解释这个 C++ 函数如何返回一个数组