并行C++调用函数

Calling a Function in Parallel C++

本文关键字:函数 调用 C++ 并行      更新时间:2023-10-16

我想在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";
    }
}

现场示例