Sei sulla pagina 1di 3

#include <mpi.

h>
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
int t;
int *x;
pthread_mutex_t status_mutex;
void Quick(int* x, int size, int left, int right, int pivot);
void Exchange(int *a, int *b);
int main(int argc, char* argv[])
{
int pivot;
int nelements;
nelements = atoi(argv[1]);
int my_rank;
int comm_size;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
MPI_Comm_size(MPI_COMM_WORLD, &comm_size);
printf("my_rank is %d \n", my_rank);
printf("comm_size is %d \n", comm_size);
/*if((comm_size%2) != 0)
{
printf("Error: number of cores not divisble by 2. \n");
printf("Exiting. \n");
exit(0);
}
printf("nelements is: %d", nelements);
if((nelements%comm_size) != 0)
{
printf("Error: number of elements not dibisble by number of cores. \n");
printf("Exiting. \n");
exit(0);
}*/
printf("hw3_3 @ 3 \n");
int localRange = nelements/comm_size;
int localStart = my_rank*localRange;
int localStop = localStart + localRange;

double startT;
double stopT;
double totalT;
double MPI_Wtime(void);
void *status;
x = (int *) malloc(sizeof(int) * nelements);
int i;
for(i = 0; i < nelements; i++)
{
x[i] = rand() % 100;
}
startT = MPI_Wtime();
printf("my_rank = %d", my_rank);
if(my_rank == 0)
{
for(i=1; i< comm_size; i++)
{
pivot = x[localStart];
MPI_Status status;
MPI_Recv((void*) &x[i], localRange, MPI_INT, i, 0, MPI_C
OMM_WORLD, &status);
Quick(x, localRange, localStart, localStop, pivot);
}
}
else
{
MPI_Send((void*) &x[i], localRange, MPI_INT, 0, 0, MPI_COMM_WORL
D);
printf("pivot = %d \n", pivot);
Quick(x, localRange, localStart, localStop, pivot);
}
MPI_Finalize();
stopT = MPI_Wtime();
totalT = stopT - startT;
printf("\nThe total run time was: %12.6f seconds \n", totalT);
for(i=0; i < nelements; i++)
{
printf("\n%d", x[i]);
}
return 0;
}

void Quick(int* x, int size, int left, int right, int pivot)
{
int i;
int j;
if (left < right)
{
i = left;
j = right-1;
if (i < j)
{
do
{
do
{
i++;
}while (x[i] < pivot);
do
{
j--;
}while (x[j] > pivot);
Exchange(&x[i], &x[j]);
}while(j > i);
printf("\nPRE%d", x[i]);
Exchange(&x[i], &x[j]);
Exchange(&x[i], &x[right-1]);
printf("\nPOST%d", x[i]);
}
}
}
void Exchange(int *a, int *b)
{
int temp = a;
a = b;
b = temp;
}

Potrebbero piacerti anche