tags:

views:

224

answers:

1

Hello,

I am learning MPI, so i though i could write simple odd even sort for 2 processors. First processor sorts even array elements and second odd array elements. I'm using global array for 2 processors, so i need synchronization(something like semaphore or lock variable) because i get bad results. How this problem is solved in MPI ? My code:

#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 ; 
}
A: 

Each of your two MPI tasks is working on a different copy of the array. You need to explicitly merge the two arrays using something like MPI_Send() and MPI_Recv() or one of the more complex MPI functions.

MPI is a distributed memory programming model, not shared memory like OpenMP or threads.

Dermot
Thanks. Now i know differences from MPI and OpenMP
kesrut