并行调用一个函数多次

并行调用一个函数多次

本文介绍了并行调用一个函数多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想多次调用具有不同arg值的函数.为了使执行速度更快,我想在不考虑其实现的情况下调用该函数.

I want to call a function with different value of arg many times. To make the execution faster I want to call the function without considering its implementation.

在循环中,我将arg传递给函数并调用它,现在我的程序不应该等待该函数执行并再次循环,相反,它不应该考虑该函数尚未完成第一个循环,因此应该继续执行然后一次又一次地调用该函数,直到循环结束.

Inside a loop i pass the arg to the function and call it now my program should not wait for the function to execute and loop again, instead it should not consider that the function has not completed for the first loop it should go ahead and call the function again and again till the loop ends.

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

how to use fork and threads to do this , which one will be faster and a skeleton of code will help ?Lets say my function is void foo(arg1,arg2)

推荐答案

如果这是一个计算量大的方法,那么为每个调用生成一个线程/进程不是一个好主意(事实上,它永远不是一个好主意) !).

If it's a computationally intensive method then it's not a good idea to spawn a thread/process for each call (as a matter of fact, it's never a good idea!).

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

You can efficiently parallelize the for loop using openmp:

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

这将根据可用CPU内核的数量创建多个线程,然后在其中拆分迭代.您可以使用schedule子句进一步调整计划.

This will create a number of threads according to the number of available CPU cores and then split the iterations among them. You can further tune the scheduling using the schedule clause.

这篇关于并行调用一个函数多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 12:28