0

我正在学习 MPI,所以我虽然可以为 2 个处理器编写简单的奇偶排序。第一个处理器对偶数数组元素和第二个奇数数组元素进行排序。我正在为 2 个处理器使用全局数组,所以我需要同步(比如信号量或锁变量),因为我得到了不好的结果。这个问题在 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 ; 
}
4

1 回答 1

1

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

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

于 2009-10-21T14:33:57.240 回答