Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <mpi.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <time.h>
- int main(int argc, char* argv[])
- {
- int N = atoi(argv[1]); // number of items each worker should generate
- int H = atoi(argv[2]); // highest value, the range 1:H
- //0 shares N & H with all workers
- //less than 20 workers in all cases
- //workers each generate a list of N values from 1 to H
- //0 gathers these lists into a single BigList
- //0 shares BigList with all workers
- //workers each computer local sum, max, min for their data
- //boss collects sum, max, min to find global values
- //boss reports global values
- MPI_Init(NULL, NULL);
- // Find out rank, size
- int my_rank;
- int world_size;
- MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
- MPI_Comm_size(MPI_COMM_WORLD, &world_size);
- MPI_Status status;
- /////////////////////////////////////////////
- int NHArray[2];
- NHArray[0] =N;
- NHArray[1] = H;
- int list[N];
- int calcs[3];
- int globalSum = 0;
- int globalMax = 1;
- int globalMin = H;
- int bigN =(N * (world_size - 1));
- int bigList[bigN];
- if (my_rank == 0)
- {
- int offset;
- MPI_Bcast(NHArray, 2, MPI_INT, 0, MPI_COMM_WORLD);
- printf("Broadcasted from 0\n");
- for(int i = 1; i < world_size; i++)
- {
- MPI_Recv(list, N, MPI_INT, i , 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
- for(int j = 0; j < N; j++)
- {
- bigList[j + offset] = list[j];
- }
- offset += N;
- }
- printf("Recv from 0\n");
- MPI_Bcast(bigList, bigN, MPI_INT, 0, MPI_COMM_WORLD);
- printf("Broadcasted again from 0\n");
- for(int k = 1; k < world_size; k++)
- {
- MPI_Recv(calcs, 3, MPI_INT, k, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
- globalSum += calcs[0];
- if(calcs[1] > globalMax)
- {
- globalMax = calcs[1];
- }
- if(calcs[2] < globalMin)
- {
- globalMin = calcs[2];
- }
- }
- printf("Calculations done in 0\n");
- printf("Global Sum: %d\n", globalSum);
- printf("Global Min: %d\n", globalMin);
- printf("Global Max: %d\n", globalMax);
- }
- else
- {
- int offsetW = 0;
- int sum = 0;
- int max = 1;
- int min = H;
- MPI_Bcast(&NHArray, 2, MPI_INT, 0, MPI_COMM_WORLD);
- printf("Bcast send from worker \n");
- for(int i = 0; i < N; i++)
- {
- list[i] = rand() %H + 1;
- }
- MPI_Send(list, N, MPI_INT, 0, 0, MPI_COMM_WORLD);
- printf("Send list from worker \n");
- MPI_Bcast(bigList, bigN, MPI_INT, 0, MPI_COMM_WORLD);
- printf("Bcast from worker\n");
- for (int j = 0; j < N; j++)
- {
- sum += bigList[j + offsetW];
- if (bigList[j + offsetW] > max)
- {
- max = bigList[j + offsetW];
- }
- if(bigList[j + offsetW] < min)
- {
- min = bigList[j + offsetW];
- }
- }
- offsetW += N;
- calcs[0] = sum;
- calcs[1] = max;
- calcs[2] = min;
- MPI_Send(calcs, 3, MPI_INT, 0,0,MPI_COMM_WORLD);
- printf("Sending from worker\n");
- }
- ////////////////////////////////////////////
- MPI_Finalize();
- printf("Finalize");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement