Python-like multiprocessing in C ++

I'm new to C ++, and I'm starting from a long Python background.

I am looking for a way to run a function in parallel in C ++. I read a lot about std::async, but I'm still not very clear.

  • The following code does a really interesting thing

    #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;
    }
    

    If I run it several times, sometimes the output is what I expected:

    Message from main.
    Async call
    

    But sometimes I get something like this:

    MAessysnacg ec aflrlom main.
    

    Why isn’t happening cout? I clearly call the .get()AFTER method cout.

  • About parallel launches. In case I have a code like this:

    #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;
    }
    

    twiceWill all 10 function calls be executed simultaneously on separate kernels?

    In the case of no, is there something similar in C ++ like Python multiprocess lib?

    Basically what I'm looking for:

    n ? 1 n .

+4
1

1) result.get(); . . std::async(called_from_async) ( , ).

std::cout . , , , - . , . ( ), .

2) . , , . , ( , , ).

lib ++ ( , std). , , . forking popen syscalls.

+5

Source: https://habr.com/ru/post/1657590/


All Articles