Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <mpi.h>
- #include <stdlib.h>
- #include <math.h>
- #include "l17.h"
- int main(int argc, char** argv) {
- int rc;
- rc = MPI_Init(&argc, &argv);
- L17_CHECK_ERROR(MPI_Init, rc);
- int size;
- rc = MPI_Comm_size(MPI_COMM_WORLD, &size);
- L17_CHECK_ERROR(MPI_Comm_size, rc);
- int rank;
- rc = MPI_Comm_rank(MPI_COMM_WORLD, &rank);
- L17_CHECK_ERROR(MPI_Comm_rank, rc);
- srand(rank + 1);
- int sendcount = rand() % 7 + 1;
- double* sendbuf;
- sendbuf = (double*) malloc(sendcount * sizeof(double));
- if (sendbuf == NULL) {
- printf("Error. Couldn't allocate memory.");
- MPI_Abort(MPI_COMM_WORLD, 1);
- }
- int i;
- for (i = 0; i < sendcount; ++i)
- sendbuf[i] = sqrt(rank);
- int* recvcounts;
- if (rank == 0) {
- recvcounts = (int*) malloc(size * sizeof(int));
- if (recvcounts == NULL) {
- printf("Error. Couldn't allocate memory.");
- MPI_Abort(MPI_COMM_WORLD, 3);
- }
- }
- rc = MPI_Gather(&sendcount, 1, MPI_INT, recvcounts, 1, MPI_INT, 0, MPI_COMM_WORLD);
- L17_CHECK_ERROR(MPI_Gather, rc);
- int* displs;
- if (rank == 0) {
- displs = (int*) malloc(size * sizeof(int));
- if (displs == NULL) {
- printf("Error. Couldn't allocate memory.");
- MPI_Abort(MPI_COMM_WORLD, 4);
- }
- displs[0] = 0;
- for (i = 1; i < size; ++i)
- displs[i] = displs[i - 1] + recvcounts[i - 1];
- }
- double* recvbuf;
- int recvbufsize;
- if (rank == 0) {
- recvbufsize = displs[size - 1] + recvcounts[size - 1];
- recvbuf = (double*) malloc(recvbufsize * sizeof(double));
- if (recvbuf == NULL) {
- printf("Error. Couldn't allocate memory.");
- MPI_Abort(MPI_COMM_WORLD, 2);
- }
- }
- rc = MPI_Gatherv(sendbuf, sendcount, MPI_DOUBLE, recvbuf, recvcounts, displs, MPI_DOUBLE, 0, MPI_COMM_WORLD);
- L17_CHECK_ERROR(MPI_Gatherv, rc);
- free(sendbuf);
- if (rank == 0) {
- FILE* outputp = fopen("apr1-gather-gatherv.dat", "w");
- if (outputp == NULL) {
- printf("Error. Couldn't open the file for output values.");
- MPI_Abort(MPI_COMM_WORLD, 5);
- }
- for (i = 0; i < size; ++i) {
- int j;
- for (j = 0; j < recvcounts[i]; ++j)
- fprintf(outputp, "%f ", recvbuf[displs[i] + j]);
- fprintf(outputp, "\n");
- }
- free(displs);
- free(recvcounts);
- fclose(outputp);
- free(recvbuf);
- }
- MPI_Finalize();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement