Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include "mpi.h"
- int main(int argc, char *argv[]) {
- int numtasks, rank, N;
- int result=0;
- int product;
- int* a;
- int* b;
- //initializing MPI
- MPI_Init(&argc, &argv);
- //get size
- MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
- //get rank
- MPI_Comm_rank(MPI_COMM_WORLD, &rank);
- //have to broadcast N still to distribute it
- MPI_Bcast(&N, 1, MPI_INT, 0, MPI_COMM_WORLD);
- if(rank == 0) {
- N = 100; //simulate reading in user input
- }
- //if(rank == 0) {
- // printf("Enter size: %d\n", N);
- // scanf("%d", &N);
- //}
- if(rank == 0) {
- //pointers to dynamically allocate memory for 2 arrays on each node. done in master thread
- a=(int*)malloc(N*sizeof(int));
- b=(int*)malloc(N*sizeof(int));
- //hardcoding each value of vectors to 2
- for(int i = 0; i < N; i++) {
- a[i]=b[i]=2;
- }
- }
- int new_N; //new_N: new discrete variable to sum counts
- if(rank < (N%numtasks)) {
- new_N = N/numtasks + 1;
- }
- else {
- new_N = N/numtasks;
- }
- //array to hold count for each rank
- int* sendcount = (int*)malloc(N*sizeof(int));
- //array that holds displacement from start of sendbuf to take the data
- int* displs = (int*)malloc(N*sizeof(int));
- //fill sendcount array
- for(int i = 0; i < new_N; i++) {
- sendcount[i] = new_N;
- displs[i] = i*sendcount[i];
- }
- //takes care of remainder
- for(int i = N%numtasks; i < numtasks; i++) {
- sendcount[i] = N/numtasks;
- displs[i] = i*sendcount[i];
- }
- MPI_Scatterv(a, sendcount, displs, MPI_INT, a, new_N, MPI_INT, 0, MPI_COMM_WORLD);
- MPI_Scatterv(b, sendcount, displs, MPI_INT, a, new_N, MPI_INT, 0, MPI_COMM_WORLD);
- //actually calculating dot product
- for(int i = 0; i < N; i++){
- result+=(a[i] * b[i]);
- }
- printf("%d\n", rank);
- //collect individual sums from processors for final result
- MPI_Allreduce(MPI_IN_PLACE, &result, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
- printf("Rank: %d: Result: %d\n", rank, result);
- //finished with MPI
- MPI_Finalize();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement