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