多次并行调用函数

我想多次调用具有不同arg值的函数。 为了使执行更快,我想调用函数而不考虑它的实现。

在循环内部我将arg传递给函数并调用它现在我的程序不应该等待函数执行并再次循环,而是它不应该认为函数没有完成第一个循环它应该继续并调用一次又一次地起作用直到循环结束。

如何使用fork和threads来做到这一点,哪一个更快,一个代码框架会有帮助? 让我说我的函数是void foo(arg1,arg2)

如果它是一个计算密集型方法,那么为每个调用生成一个线程/进程并不是一个好主意(事实上,它绝不是一个好主意!)。

您可以使用openmp高效并行化for循环:

#pragma omp parallel for for(int i = 0; i < N; i++) { int arg1 = ... int arg2 = ... foo(arg1, arg2); } 

这将根据可用CPU核心数创建多个线程,然后在它们之间拆分迭代。 您可以使用schedule子句进一步调整调度。

您需要异步实现proactor模式。

这是一个例子,使用boost::asioboost::thread

 #include  using namespace std; #include  #include  // your function, with its arguments void foo(int x, int y) { cout << x << " * " << y << " = " << x * y << "\n"; } int main() { boost::asio::io_service svc; boost::asio::io_service::work w(svc); // create a thread to run the io_service proactor boost::thread thread(boost::bind(&boost::asio::io_service::run, &svc)); for(int z = 0; z < 32; ++z) { // bind the function to its arguments to // be called in the context of the running // thread svc.post(boost::bind(&f, 2, z)); } boost::this_thread::sleep(boost::posix_time::milliseconds(1000)); svc.stop(); thread.join(); } 

这里的好处是,如果需要,可以通过从线程池调用boost::asio::io_service::run来轻松扩展。

就像Tudor所推荐的那样,我也会使用Intel TBB或Microsoft PPL中的parallel_for模式算法。

如果你真的想为每个函数生成一个need线程,你可以这样做:

 #include  #include  void foo(arg1, arg2) { //do stuff } int main() { std::vector threads; for(auto i = x; i != y; ++i) threads.emplace_back(foo, arg1, arg2); for(auto& i: threads) i.join(); }