| 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 |
|
|---|
| 10 | void master (void);
|
|---|
| 11 | void slave (void);
|
|---|
| 12 |
|
|---|
| 13 | int 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 |
|
|---|
| 28 | void 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 |
|
|---|
| 47 | void 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 | }
|
|---|