gpt4 book ai didi

C++ 中类似 Python 的多处理

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:42:43 24 4
gpt4 key购买 nike

我是 C++ 的新手,而且我有很长的 Python 背景。

我正在寻找一种在 C++ 中并行运行函数的方法。我阅读了很多关于 std::async 的内容,但对我来说仍然不是很清楚。

  1. 下面的代码做了一些非常有趣的事情

    #include <future>
    #include <iostream>

    void called_from_async() {
    std::cout << "Async call" << std::endl;
    }

    int main() {
    //called_from_async launched in a separate thread if possible
    std::future<void> result( std::async(called_from_async));

    std::cout << "Message from main." << std::endl;

    //ensure that called_from_async is launched synchronously
    //if it wasn't already launched
    result.get();

    return 0;
    }

    如果我多次运行它,有时输出是我所期望的:

    Message from main.
    Async call

    但有时我会得到这样的结果:

    MAessysnacg ec aflrlom main.

    为什么 cout 不是先发生?我清楚地在 cout 之后调用了 .get() 方法。

  2. 关于并行运行。如果我有这样的代码:

    #include <future>
    #include <iostream>
    #include <vector>

    int twice(int m) {
    return 2 * m;
    }

    int main() {
    std::vector<std::future<int>> futures;

    for(int i = 0; i < 10; ++i) {
    futures.push_back (std::async(twice, i));
    }

    //retrive and print the value stored in the future
    for(auto &e : futures) {
    std::cout << e.get() << std::endl;
    }

    return 0;
    }

    twice 函数的所有 10 次调用将同时在不同的内核上运行?

    如果不是,C++ 中是否有类似 Python multiprocess lib 的东西?

    主要是我要搜索的内容:

    我写了一个函数,并用 n 个输入调用它?multiprocessing?并且它会同时在n个节点上运行该函数1次。

最佳答案

1) result.get(); 不启动线程。它只是等待结果。并行线程通过 std::async(called_from_async) 调用启动(或在编译器决定的任何时候)。

但是 std::cout 保证是内部线程安全的。因此,您向我们展示的结果不应该永远不会发生。有一个竞争条件,但你不能像那样混合两个输出。如果它真的发生了(我对此表示怀疑),那么您可能正在处理编译器错误。

2) 您的调用将并行进行。有多少内核取决于您机器上运行的操作系统和其他进程。但是很有可能会使用所有的东西(假设您可以控制整个生态系统并且没有其他 cpu 密集型进程在后台运行)。

C++ 没有类似多处理的库(至少在标准中没有)。如果你想运行子进程,那么有几个选项,例如 fork 或 popen 系统调用。

关于C++ 中类似 Python 的多处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40016373/

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