【发布时间】:2016-10-13 08:50:56
【问题描述】:
我是 C++ 的新手,我来自 Python 的长期背景。
我正在寻找一种在 C++ 中并行运行函数的方法。我读了很多关于std::async 的文章,但对我来说仍然不是很清楚。
-
下面的代码做了一些非常有趣的事情
#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()方法。 -
关于并行运行。如果我有这样的代码:
#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 个输入调用它?多处理?它会同时在n个节点上运行该函数1次。
【问题讨论】:
-
由于
std::cout是内部同步的,您的结果应该永远发生。这实际上是您看到的确切结果吗?如果是这样,那就是编译器错误。 — 另一条评论,请不要在您发布的代码中添加行号,这会使其他人更难复制粘贴来尝试代码。 -
@GáborErdős 您误解了异步期货的运作方式。当
.get被调用时它们不会被执行——get只是确保执行已经完成,但是它们很可能会提前开始执行。否则,为什么您会期望您的第二个代码有不同的行为?毕竟,get在你所有的期货上都被依次调用。 -
@GáborErdős 取决于执行策略……但总的来说(特别是在
std::async的情况下),是的。但是,这仍然不能解释您的乱码输出,请参阅我的第一条评论。 -
@GáborErdős 混合
cerr和cout应该是这种混合文本发生的唯一方式。或者当您使用不同的输出时,但在这种情况下,您的示例将是错误的。 -
@Pod C++ 在标准库中有一个线程库(头文件
<thread>)。 pthreads 不是标准的 C++,因此需要考虑可移植性问题。它是 C。
标签: python c++ asynchronous multiprocessing