source: CIVL/examples/MPI/sum_array.c@ 5773b57e

1.23 2.0 main test-branch
Last change on this file since 5773b57e was 5773b57e, checked in by Ziqing Luo <ziqing@…>, 12 years ago

MPI examples
I think the "cpi_mc" program which calculates Pi with Monte Carlo algorithm will be the most complicated one.

The rest four have similar complexity level.

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

  • Property mode set to 100644
File size: 1.6 KB
Line 
1/* Sum of an array - First 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 //Initialization of MPI
16 MPI_Init (&argc, &argv);
17 //myrank will contain the rank of the process
18 MPI_Comm_rank (MPI_COMM_WORLD, &myrank);
19 //The part of the program which will be executed is decided
20 if (myrank == 0)
21 master ();
22 else
23 slave ();
24 MPI_Finalize ();
25 return 0;
26}
27
28void master (void) {
29 float array[N];
30 double mysum = 0, tmpsum;
31 unsigned long long i;
32 MPI_Status status;
33 //Initialization of the array
34 for (i = 0; i < N; i++)
35 array[i] = i + 1;
36 //The array is divided by two and each part is sent to the slaves
37 MPI_Send (array, N / 2, MPI_FLOAT, 1, MSG_DATA, MPI_COMM_WORLD);
38 MPI_Send (array + N / 2, N / 2, MPI_FLOAT, 2, MSG_DATA, MPI_COMM_WORLD);
39 //The master receive the result from the slaves
40 MPI_Recv (&tmpsum, 1, MPI_DOUBLE, 1, MSG_RESULT, MPI_COMM_WORLD, &status);
41 mysum += tmpsum;
42 MPI_Recv (&tmpsum, 1, MPI_DOUBLE, 2, MSG_RESULT, MPI_COMM_WORLD, &status);
43 mysum += tmpsum;
44 printf ("%lf\n", mysum);
45}
46
47void slave (void) {
48 float array[N];
49 double sum;
50 unsigned long long i;
51 MPI_Status status;
52 //The slave receives the array from the master
53 MPI_Recv (array, N / 2, MPI_FLOAT, 0, MSG_DATA, MPI_COMM_WORLD, &status);
54 for (i = 0, sum = 0; i < N / 2; i++)
55 sum += array[i];
56 //The result is send to the master
57 MPI_Send (&sum, 1, MPI_DOUBLE, 0, MSG_RESULT, MPI_COMM_WORLD);
58}
Note: See TracBrowser for help on using the repository browser.