Skip to content

Instantly share code, notes, and snippets.

@tuytoosh
Last active January 19, 2018 10:38
Show Gist options
  • Save tuytoosh/34b4a574d102993b45be9d90cf11566c to your computer and use it in GitHub Desktop.
Save tuytoosh/34b4a574d102993b45be9d90cf11566c to your computer and use it in GitHub Desktop.
scatter and gather simple example in c
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
#include "mpi.h"
#pragma comment(lib, "msmpi.lib")
void main(int argc, char *argv[])
{
int myid, numprocs;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
int *InputArr = new int[numprocs];
if(myid == 0)
{
srand(time(NULL));
for(int i = 0; i < numprocs; i++)
InputArr[i] = rand() % 5;
}
int *rec = new int[1];
MPI_Scatter(InputArr, 1, MPI_INT, rec, 1, MPI_INT, 0, MPI_COMM_WORLD);
printf("num in process %d : %d", myid, *rec);
int *gather = new int[1];
MPI_Gather(&rec[0], 1, MPI_INT, &gather[0], 1, MPI_INT, 0, MPI_COMM_WORLD);
if(myid == 0)
{
int my_sum = 0;
for(int i = 0; i < numprocs; i++)
{
my_sum += *(gather+i);
}
printf("\n result : %d \n", my_sum);
}
MPI_Finalize();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment