2009-10-03 51 views
0

我正在学习MPI,所以我虽然可以为2个处理器编写简单的奇数偶数排序。第一个处理器对偶数数组和第二个奇数数组元素进行排序。我为2个处理器使用全局数组,所以我需要同步(像信号量或锁变量),因为我得到了不好的结果。 MPI如何解决这个问题?我的代码:MPI阵列同步

#include "mpi.h" 
#include <stdio.h> 

int main(int argc, char *argv[]) 
{ 
    int rank, size ; 
    int n = 6 ; 
    int array[6] = { 5, 6, 1, 2, 4, 10} ; 
    MPI_Init(&argc, &argv) ; 
    MPI_Comm_rank(MPI_COMM_WORLD, &rank) ; 
    MPI_Comm_size(MPI_COMM_WORLD, &size) ; 
    if (size == 2) 
    { 
    int sorted1; 
    int sorted2; 
    if (rank == 0) 
    { 
     sorted1 = 0 ; 
    while (!sorted1) 
     { 
    sorted1 = 1 ; 
      int x; 
    for (x=1; x < n; x += 2) 
    { 
      if (array[x] > array[x+1]) 
     { 
       int tmp = array[x] ; 
    array[x] = array[x+1] ; 
    array[x+1] = tmp ; 
    sorted1 = 0 ; 
      } 
      } 
     } 
    } 
    if (rank == 1) 
    { 
     sorted2 = 0 ; 
    while (!sorted2) 
     { 
    sorted2 = 1 ; 
      int x; 
    for (x=0; x < n-1; x += 2) 
    { 
      if (array[x] > array[x+1]) 
     { 
       int tmp = array[x] ; 
    array[x] = array[x+1] ; 
    array[x+1] = tmp ; 
    sorted2 = 0 ; 
      } 
      } 
     } 

    } 
    } 
    else if (rank == 0) printf("Only 2 processors supported!\n") ; 
    int i=0 ; // bad output printed two times.. 
    for (i=0; i < n; i++) 
    { 
     printf("%d ", array[i]) ; 
    } 
    printf("\n") ; 

    MPI_Finalize() ; 
    return 0 ; 
} 

回答

1

您的两个MPI任务中的每一个都在数组的不同副本上工作。您需要使用类似MPI_Send()和MPI_Recv()或更复杂的MPI函数之一来显式合并两个数组。

MPI是一种分布式内存编程模型,不像OpenMP或线程那样是共享内存。

+0

谢谢。现在我知道MPI和OpenMP的不同之处 – kesrut 2009-11-30 15:59:00