-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathejercicio4.c
More file actions
69 lines (55 loc) · 1.63 KB
/
ejercicio4.c
File metadata and controls
69 lines (55 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*butterlfy
*/
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
const int MAX_CONTRIB = 20;
int Global_sum(int my_contrib, int my_rank, int p, MPI_Comm comm);
void Print_results(char title[], int value, int my_rank, int p,
MPI_Comm comm);
int main(void) {
int p, my_rank;
MPI_Comm comm;
int my_contrib;
int sum;
MPI_Init(NULL, NULL);
comm = MPI_COMM_WORLD;
MPI_Comm_size(comm, &p);
MPI_Comm_rank(comm, &my_rank);
srandom(my_rank);
my_contrib = random() % MAX_CONTRIB;
Print_results("Valores de procesos ", my_contrib, my_rank, p, comm);
sum = Global_sum(my_contrib, my_rank, p, comm);
Print_results("Procesos totales ", sum, my_rank, p, comm);
MPI_Finalize();
return 0;
}
void Print_results(char title[], int value, int my_rank, int p, MPI_Comm comm) {
int* vals = NULL, q;
if (my_rank == 0) {
vals = malloc(p*sizeof(int));
MPI_Gather(&value, 1, MPI_INT, vals, 1, MPI_INT, 0, comm);
printf("%s:\n", title);
for (q = 0; q < p; q++)
printf("Proc %d > %d\n", q, vals[q]);
printf("\n");
free(vals);
} else {
MPI_Gather(&value, 1, MPI_INT, vals, 1, MPI_INT, 0, comm);
}
}
int Global_sum(int my_contrib, int my_rank, int p, MPI_Comm comm) {
int sum = my_contrib;
int temp;
int partner;
unsigned bitmask = 1;
while (bitmask < p) {
partner = my_rank ^ bitmask;
MPI_Sendrecv(&sum, 1, MPI_INT, partner, 0,
&temp, 1, MPI_INT, partner, 0,
comm, MPI_STATUS_IGNORE);
sum += temp;
bitmask <<= 1;
}
return sum;
}