C++中类似Python的多处理

Gáb*_*dős 4 c++ python asynchronous multiprocessing

我是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;
    }
    
    Run Code Online (Sandbox Code Playgroud)

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

    Message from main.
    Async call
    
    Run Code Online (Sandbox Code Playgroud)

    但有时我得到这样的东西:

    MAessysnacg ec aflrlom main.
    
    Run Code Online (Sandbox Code Playgroud)

    为什么不cout首先发生?我明确地称之为.get()方法cout.

  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;
    }
    
    Run Code Online (Sandbox Code Playgroud)

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

    如果没有,C++中是否有像Python 进程库一样的东西?

    主要是我要搜索的内容:

    我编写了一个函数,用多个输入调用n多个输入?它将同时在n个节点上运行该函数1次.

fre*_*ish 5

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

但是std::cout保证内部线程安全.所以你向我们展示的结果不应该发生.有一个竞争条件,但你不能混合这两个输出.如果它确实发生(我怀疑)那么你可能正在处理编译器错误.

2)您的电话将并行运行.在多少内核上依赖于操作系统和机器上运行的其他进程.但是很有可能会使用所有内容(假设您可以控制整个生态系统,并且后台没有其他CPU密集型进程在运行).

C++没有类似多处理的lib(至少不在std中).如果您希望运行子进程,那么有几个选项,例如分叉或popen系统调用.