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 ;
}