| 1 | #include<mpi.h>
|
|---|
| 2 | #include<civl-mpi.cvh>
|
|---|
| 3 | #include<civlc.cvh>
|
|---|
| 4 | #include<string.h>
|
|---|
| 5 | #include<stdlib.h>
|
|---|
| 6 |
|
|---|
| 7 | /* A collective sum-reduction operation */
|
|---|
| 8 |
|
|---|
| 9 | /*@ \mpi_collective(comm, P2P):
|
|---|
| 10 | @ requires datatype == MPI_INT;
|
|---|
| 11 | @ requires 0<count && count*\mpi_extent(datatype) < 5;
|
|---|
| 12 | @ requires \mpi_valid(sendbuf, count, datatype);
|
|---|
| 13 | @ requires \mpi_valid(recvbuf, count, datatype);
|
|---|
| 14 | @ requires \mpi_agree(root) && \mpi_agree(count * datatype);
|
|---|
| 15 | @ requires 0 <= root && root < \mpi_comm_size;
|
|---|
| 16 | @ behavior root:
|
|---|
| 17 | @ assumes \mpi_comm_rank == root;
|
|---|
| 18 | @ ensures \forall integer i; 0<= i && i <count ==>
|
|---|
| 19 | @ recvbuf[i] == \sum(0, \mpi_comm_size-1,
|
|---|
| 20 | @ \lambda int k; \on(k, sendbuf)[i]);
|
|---|
| 21 | @ waitsfor root;
|
|---|
| 22 | @
|
|---|
| 23 | @*/
|
|---|
| 24 | int reduce_sum(int * sendbuf, int * recvbuf, MPI_Datatype datatype,
|
|---|
| 25 | int count, int root, MPI_Comm comm) {
|
|---|
| 26 | int rank;
|
|---|
| 27 |
|
|---|
| 28 | MPI_Comm_rank(comm, &rank);
|
|---|
| 29 | if (rank != root)
|
|---|
| 30 | MPI_Send(sendbuf, count, datatype, root, REDUCE_TAG, comm);
|
|---|
| 31 | else {
|
|---|
| 32 | int nprocs;
|
|---|
| 33 | int size;
|
|---|
| 34 | int * sum;
|
|---|
| 35 |
|
|---|
| 36 | MPI_Comm_size(comm, &nprocs);
|
|---|
| 37 | size = count * sizeof(int);
|
|---|
| 38 | sum = (int *)malloc(sizeof(int) * count);
|
|---|
| 39 | memcpy(sum, sendbuf, size);
|
|---|
| 40 | for (int i = 0; i<nprocs; i++) {
|
|---|
| 41 | if (i != root){
|
|---|
| 42 | MPI_Recv(recvbuf, count, datatype, i, REDUCE_TAG, comm, MPI_STATUS_IGNORE);
|
|---|
| 43 |
|
|---|
| 44 | for (int i = 0; i < count; i++)
|
|---|
| 45 | sum[i] = sum[i] + recvbuf[i];
|
|---|
| 46 | }
|
|---|
| 47 | }
|
|---|
| 48 | memcpy(recvbuf, sum, size);
|
|---|
| 49 | free(sum);
|
|---|
| 50 | }
|
|---|
| 51 |
|
|---|
| 52 | return 0;
|
|---|
| 53 | }
|
|---|