Skip to content

Instantly share code, notes, and snippets.

@IuryAlves
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IuryAlves/20813c48668e74a8d83f to your computer and use it in GitHub Desktop.
Save IuryAlves/20813c48668e74a8d83f to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
void print(int vector[], int process, int size){
// imprime todos os numeros no vetor
int i;
printf("processo: %d \n", process);
for(i = 0; i < size ; i++){
printf("%d ", vector[i]);
}
printf("\n");
}
int sum_largest_vector(int vector[], int vector_size){
// soma todos os numeros no vetor
int i, sum = 0;
for(i = 0; i < vector_size; i++){
sum += vector[i];
}
return sum;
}
int main (int argc, char **argv) {
int vetor_size = 10, vector_sum = 0;
int num_received = 0, proccess = 1;
int i, rank, size, type=99;
MPI_Status status;
// inicializa o mpi
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int *vetor_total = (int*) calloc (10*size, sizeof(int));
int *vetor = (int*) calloc (vetor_size, sizeof(int));
srand((unsigned) time(NULL));
if (rank == 0) {
// gera numeros aleatorios
for(i = 0; i < 10* size; i++){
vetor_total[i] = rand() % 100;
}
}
// divide os dados entre processos
MPI_Scatter(vetor_total, vetor_size, MPI_INT, vetor, vetor_size, MPI_INT, 0, MPI_COMM_WORLD);
if (rank != 0){
// soma os dados no vetor que foi enviado por MPI_Scatter
vector_sum = sum_largest_vector(vetor, vetor_size);
// envia a soma para o processo root
MPI_Send(&vector_sum, 1, MPI_INT, 0, type, MPI_COMM_WORLD);
}else{
for(i = 1; i < size; i++){
// receve as somas dos processos escravos
MPI_Recv(&num_received, 1, MPI_INT, i, type, MPI_COMM_WORLD, &status);
if (num_received > vector_sum){
vector_sum = num_received;
proccess = i;
}
}
printf("maior soma: %d do processo %d \n", vector_sum, proccess);
}
MPI_Finalize();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment