2009-10-03 65 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