Recursion 通过MPI并行化递归函数?
我们可以使用MPI并行化递归函数吗? 我正在尝试并行化快速排序函数,但不知道它是否在MPI中工作,因为它是递归的。我还想知道我应该在哪里做平行区域Recursion 通过MPI并行化递归函数?,recursion,mpi,Recursion,Mpi,我们可以使用MPI并行化递归函数吗? 我正在尝试并行化快速排序函数,但不知道它是否在MPI中工作,因为它是递归的。我还想知道我应该在哪里做平行区域 // quickSort.c #include <stdio.h> void quickSort( int[], int, int); int partition( int[], int, int); void main() { int a[] = { 7, 12, 1, -2, 0, 15, 4, 11, 9};
// quickSort.c
#include <stdio.h>
void quickSort( int[], int, int);
int partition( int[], int, int);
void main()
{
int a[] = { 7, 12, 1, -2, 0, 15, 4, 11, 9};
int i;
printf("\n\nUnsorted array is: ");
for(i = 0; i < 9; ++i)
printf(" %d ", a[i]);
quickSort( a, 0, 8);
printf("\n\nSorted array is: ");
for(i = 0; i < 9; ++i)
printf(" %d ", a[i]);
}
void quickSort( int a[], int l, int r)
{
int j;
if( l < r )
{
// divide and conquer
j = partition( a, l, r);
quickSort( a, l, j-1);
quickSort( a, j+1, r);
}
}
int partition( int a[], int l, int r) {
int pivot, i, j, t;
pivot = a[l];
i = l; j = r+1;
while( 1)
{
do ++i; while( a[i] <= pivot && i <= r );
do --j; while( a[j] > pivot );
if( i >= j ) break;
t = a[i]; a[i] = a[j]; a[j] = t;
}
t = a[l]; a[l] = a[j]; a[j] = t;
return j;
}
如果有另一个更简单的代码用于快速排序,我也会非常感激。从技术上讲,您可以这样做,但我担心这只在SMP中有效。阵列是否适合单个节点?如果否,则即使是第一次快速排序也无法执行
如果您确实需要使用MPI对并行系统上的数组进行排序,那么您可能需要考虑使用合并排序,当然,在开始合并块之前,仍然可以在每个节点上使用快速排序。 如果您仍然想使用快速排序,但对递归版本感到困惑,那么下面是一个非递归算法的示意图,希望它可以更容易地并行化,尽管基本上是相同的:
std::stack<std::pair<int, int> > unsorted;
unsorted.push(std::make_pair(0, size-1));
while (!unsorted.empty()) {
std::pair<int, int> u = unsorted.top();
unsorted.pop();
m = partition(A, u.first, u.second);
// here you can send one of intervals to another node instead of
// pushing it into the stack, so it would be processed in parallel.
if (m+1 < u.second) unsorted.push(std::make_pair(m+1, u.second));
if (u.first < m-1) unsorted.push(std::make_pair(u.first, m-1));
}
理论上,任何东西都可以使用MPI进行并行化,但请记住,MPI本身并没有进行任何并行化。它只是提供进程之间的通信层。只要您的所有发送和接收或集体呼叫匹配,它在大多数情况下都是正确的程序。也就是说,根据您的算法,使用MPI可能不是最有效的方法。如果您要对大量数据进行排序,使其超过一个节点的内存容量,那么使用MPI可能会很有效。在这种情况下,您可能想看看RMA一章,或者其他一些更高级别的库,这些库可能会使这种类型的应用程序UPC、Co array Fortran、SHMEM等变得更加简单