source: CIVL/mods/dev.civl.abc/examples/mpi/sum_array.c

main
Last change on this file was aad342c, checked in by Stephen Siegel <siegel@…>, 3 years ago

Performing huge refactor to incorporate ABC, GMC, and SARL into CIVL repo and use Java modules.

git-svn-id: svn://vsl.cis.udel.edu/civl/trunk@5664 fb995dde-84ed-4084-dfe6-e5aef3e2452c

  • Property mode set to 100644
File size: 1.6 KB
Line 
1/* Sum of an array - Second parallel version */
2
3 #include <stdio.h>
4 #include <mpi.h>
5
6 #define N 100000
7 #define MSG_DATA 100
8 #define MSG_RESULT 101
9
10void master (void);
11void slave (void);
12
13int main (int argc, char **argv) {
14 int myrank;
15 MPI_Init (&argc, &argv);
16 MPI_Comm_rank (MPI_COMM_WORLD, &myrank);
17 if (!myrank)
18 master ();
19 else
20 slave ();
21 MPI_Finalize ();
22 return 0;
23}
24
25void master (void) {
26 float array[N];
27 double mysum, tmpsum;
28 unsigned long long step, i;
29 int size;
30 MPI_Status status;
31 //Initialization of the array
32 for (i = 0; i < N; i++)
33 array[i] = i + 1;
34 MPI_Comm_size (MPI_COMM_WORLD, &size);
35 if (size != 1)
36 step = N / (size - 1);
37 //The array is divided by the number of slaves
38 for (i = 0; i < size - 1; i++)
39 MPI_Send (array + i * step, step, MPI_FLOAT, i + 1, MSG_DATA, MPI_COMM_WORLD);
40 //The master completes the work if necessary
41 for (i = (size - 1) * step, mysum = 0; i < N; i++)
42 mysum += array[i];
43 //The master receives the results in any order
44 for (i = 1; i < size; mysum += tmpsum, i++)
45 MPI_Recv (&tmpsum, 1, MPI_DOUBLE, MPI_ANY_SOURCE, MSG_RESULT, MPI_COMM_WORLD, &status);
46 printf ("%lf\n", mysum);
47}
48
49void slave (void) {
50 float array[N];
51 double sum;
52 unsigned long long i;
53 int count;
54 MPI_Status status;
55 MPI_Recv (array, N, MPI_FLOAT, 0, MSG_DATA, MPI_COMM_WORLD, &status);
56 //The slave finds the size of the array
57 MPI_Get_count (&status, MPI_FLOAT, &count);
58 for (i = 0, sum = 0; i < count; i++)
59 sum += array[i];
60 MPI_Send (&sum, 1, MPI_DOUBLE, 0, MSG_RESULT, MPI_COMM_WORLD);
61}
Note: See TracBrowser for help on using the repository browser.