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.
std::async
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.
cout
.get()
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?
twice
In the case of no, is there something similar in C ++ like Python multiprocess lib?
Basically what I'm looking for:
n ? 1 n .
1) result.get(); . . std::async(called_from_async) ( , ).
result.get();
std::async(called_from_async)
std::cout . , , , - . , . ( ), .
std::cout
2) . , , . , ( , , ).
lib ++ ( , std). , , . forking popen syscalls.
popen
Source: https://habr.com/ru/post/1657590/More articles:mysql to mongodb и преобразование запросов - mongodbSQL left outer join on multiple columns - sqlCTE parallel queries for writing operations in PostgreSQL - postgresqlHow to pass POST data to Python requests? - pythonIs there an emacs game to control the cursor? - emacsRegular expression search '\ n' - pythonNested loop to execute during loop - c ++Using dplyr inside a function, a non-standard estimate is rflexbox div turns off screen on small screen - htmlКонсольные приложения в С# создают странный эффект для других приложений - c#All Articles