source: CIVL/examples/mpi/collective/vectorSum.c@ 77030d0

1.23 2.0 acw/focus-triggers main test-branch
Last change on this file since 77030d0 was 6546348, checked in by Manchun Zheng <zmanchun@…>, 11 years ago

added vector addition using MPI_Reduce

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

  • Property mode set to 100644
File size: 1.6 KB
Line 
1/**
2 * This is a simple program to demonstrate the correct usage of two MPI colletive operations,
3 * i.e., they have to be executed in the same order for each process.
4 */
5
6#include<mpi.h>
7#include<stdlib.h>
8#include<assert.h>
9#include<stdio.h>
10
11#define SIZE 5
12
13int main()
14{
15 int argc;
16 char** argv;
17 int rank;
18 int procs;
19 int* sendBuf;
20 int* rcvBuf;
21 int* sum;
22
23 MPI_Init(&argc,&argv);
24 MPI_Comm_size(MPI_COMM_WORLD, &procs);
25 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
26
27 if (rank == 0) {
28 sendBuf = (int*)malloc(sizeof(int)*procs);
29 sum = (int*)malloc(sizeof(int)*procs);
30 for(int i=0; i < procs; i++){
31 sendBuf[i] = i;
32 sum[i] = 0;
33 }
34 }else{
35 sum = (int*)malloc(sizeof(int));
36 sendBuf = (int*)malloc(sizeof(int));
37 }
38 rcvBuf = (int*)malloc(sizeof(int)*procs);
39
40 MPI_Scatter(sendBuf, 1, MPI_INT, rcvBuf, 1, MPI_INT, 0, MPI_COMM_WORLD);
41
42 *sendBuf = *rcvBuf;
43
44 MPI_Allgather(sendBuf, 1, MPI_INT, rcvBuf, 1, MPI_INT, MPI_COMM_WORLD);
45
46 printf("Vector process %d is: (", rank);
47 for(int i=0; i<procs; i++){
48 printf("%d", rcvBuf[i]);
49 if(i != procs-1)
50 printf(", ");
51 assert(i == rcvBuf[i]);
52 }
53 printf(")\n");
54
55 MPI_Scatter(sum, 1, MPI_INT, sum, 1, MPI_INT, 0, MPI_COMM_WORLD);
56
57 MPI_Reduce(rcvBuf, sum, procs, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
58
59 if(rank == 0){
60 printf("Vector sum is: (");
61 for(int i=0; i<procs; i++){
62 printf("%d", sum[i]);
63 if(i != procs-1)
64 printf(", ");
65 assert(i*procs == sum[i]);
66 }
67 printf(")\n");
68 }
69
70 free(sendBuf);
71 free(rcvBuf);
72 free(sum);
73 return 0;
74}
Note: See TracBrowser for help on using the repository browser.