Skip to content

Instantly share code, notes, and snippets.

@denisb411
Created December 5, 2017 16:53
Show Gist options
  • Save denisb411/d66202f6accd83ac51e3d591a10b2f34 to your computer and use it in GitHub Desktop.
Save denisb411/d66202f6accd83ac51e3d591a10b2f34 to your computer and use it in GitHub Desktop.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <pthread.h>
#include <float.h>
#include <time.h>
#include <mpi.h>
#define MASTER 0
#define N_TAREFAS 5
/*
Crie um programa em MPI com N processos, onde o processo n ́umero 0 crie uma lista de tarefas (5
conjunto de opera ̃oes matem ́aticas) e envie para cada 2 processos a mesma definindo o in ́ıcio e fim das
opera ̧c ̃oes.
*/
MPI_Status status;
int operacao1();
int operacao2();
int operacao3();
int operacao4();
int operacao5();
int main(int argc, char *argv[])
{
int numtasks,taskid,rc,numworkers,source,dest,offset,i,j;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &taskid);
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
if (numtasks < 2 ) {
printf("Need at least two MPI tasks. Quitting...\n");
MPI_Abort(MPI_COMM_WORLD, rc);
exit(1);
}
numworkers = numtasks-1;
int nprocessos=numworkers;
int listatarefas[nprocessos][N_TAREFAS];
/*---------------------------- master ----------------------------*/
if (taskid == MASTER) {
//Initiate the timer
clock_t begin = clock();
offset = 0;
for (dest=1; dest<=numworkers; dest++)
{
MPI_Send(&offset, 1, MPI_INT, dest, 1, MPI_COMM_WORLD);
offset = offset + 1;
}
/* wait for results from all worker tasks */
for (i=1; i<=numworkers; i++)
{
source = i;
MPI_Recv(&offset, 1, MPI_INT, source, 2, MPI_COMM_WORLD, &status);
MPI_Recv(&listatarefas[offset][0], N_TAREFAS, MPI_INT, source, 2, MPI_COMM_WORLD, &status);
}
//end the timer and calculate
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
for (i=0; i<nprocessos; i++) {
for (j=0; j<N_TAREFAS; j++)
printf("resultado do processo %i, tarefa %i: %i \n", i, j, listatarefas[i][j]);
}
printf("\n\n----This process took %f ----\n\n", time_spent);
}
/*---------------------------- worker----------------------------*/
if (taskid > MASTER) {
source = 0;
MPI_Recv(&offset, 1, MPI_INT, source, 1, MPI_COMM_WORLD, &status);
listatarefas[offset][0] = operacao1();
listatarefas[offset][1] = operacao2();
listatarefas[offset][2] = operacao3();
listatarefas[offset][3] = operacao4();
listatarefas[offset][4] = operacao5();
MPI_Send(&offset, 1, MPI_INT, 0, 2, MPI_COMM_WORLD);
MPI_Send(&listatarefas, N_TAREFAS, MPI_INT, 0, 2, MPI_COMM_WORLD);
}
MPI_Finalize();
}
int operacao1(){
int a = 16, b = 8, c;
c = a + b;
return c;
}
int operacao2(){
int a = 16, b = 8, c;
c = a - b;
return c;
}
int operacao3(){
int a = 16, b = 8, c;
c = a * b;
return c;
}
int operacao4(){
int a = 16, b = 8, c;
c = a / b;
return c;
}
int operacao5(){
int a = 16, b = 8, c;
c = a % b;
return c;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment