并行C++调用函数
Calling a Function in Parallel C++
我想在C++中并行调用一个函数,它等待一段时间并执行一些任务。但我不希望执行流等待函数。我考虑过以简单的方式使用 pthread,但同样,我必须等到它重新连接!
void A_Function()
{
/* Call a function which waits for some time and then perform some tasks */
/* Do not wait for the above function to return and continue performing the background tasks */
}
注意:如果我在并行调用函数时不执行后台任务,那么在下一个周期中,该函数不会给我正确的输出。
提前谢谢。
使用std::future
打包std::async
任务。在函数的头部等待未来,以确保它在下一次迭代之前完成,因为你说过下一次迭代取决于此后台任务的执行。
在下面的示例中,我使后台任务成为计数器的简单原子增量,前台任务仅返回计数器值。这仅供说明之用!
#include <iostream>
#include <future>
#include <thread>
class Foo {
public:
Foo() : counter_(0) {}
std::pair<int, std::future<void>> a_function(std::future<void>& f) {
// Ensure that the background task from the previous iteration
// has completed
f.wait();
// Set the task for the next iteration
std::future<void> fut = std::async(std::launch::async,
&Foo::background_task, this);
// Do some work
int value = counter_.load();
// Return the result and the future for the next iteration
return std::make_pair(value, std::move(fut));
}
void background_task() {
++counter_;
}
private:
std::atomic<int> counter_;
};
int main() {
// Bootstrap the procedure with some empty task...
std::future<void> bleak = std::async(std::launch::deferred, [](){});
Foo foo;
// Iterate...
for (size_t i = 0; i < 10; ++i) {
// Call the function
std::pair<int, std::future<void>> result = foo.a_function(bleak);
// Set the future for the next iteration
bleak = std::move(result.second);
// Do something with the result
std::cout << result.first << "n";
}
}
现场示例
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 类型擦除的std::function与虚拟函数调用的开销