Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Copyright 2011 Dmitry Khodakov
- Just sum up natural numbers with MPI
- coded: 1.03.11
- */
- // TODO(dimert): test on multicore machine!
- #include <mpi.h>
- #include <stdlib.h>
- #include <stdint.h>
- // mark of every message
- #define TAG 0
- void master(int last_number);
- void node();
- int main(int argc, char *argv[]) {
- int myid = 0;
- MPI_Init(&argc, &argv);
- MPI_Comm_rank(MPI_COMM_WORLD, &myid);
- if (myid == 0)
- master(atoi(argv[1]));
- else
- node();
- MPI_Finalize();
- return 0;
- }
- // master (id = 0) process, it split task and get first part of it
- // args: last_number - bottom of natural sequence.
- void master(int last_number) {
- MPI_Status stat; // status of receiving. I didn't use it here. Don't delete.
- uint32_t sended_res; // result of partial computation by node
- uint32_t res = 0; // overall result
- int numproc = 1; // number of nodes in network
- // pair of numbert for node to sum, task[0]-first, task[1]-last
- int task[2];
- // getting number of machines
- MPI_Comm_size(MPI_COMM_WORLD, &numproc);
- printf("size of world = %d\n", numproc);
- // splitting to tasks
- // TODO(dimert): dynamically change task size depending on sum size
- int task_size = last_number / numproc;
- int modulo = last_number % numproc; // counter for modulo.
- int cur_size = 0;
- printf("divided into parts of %d, size to proc, with modulo %d\n", task_size,
- modulo);
- // sending tasks
- int first_piece = (modulo == 0)? task_size : task_size + 1;
- cur_size = first_piece;
- for (int i = 1, add_count = 0; i < numproc; ++i, ++add_count) {
- task[0] = cur_size + 1;
- cur_size = task_size;
- if (add_count < modulo)
- ++cur_size;
- task[1] = cur_size;
- printf("sending from %d to %d\n", task[0], task[1]);
- MPI_Send(task, 2, MPI_INT, i, TAG, MPI_COMM_WORLD);
- }
- // first piece of computations
- for (int n = 1; n <= first_piece; ++n)
- res += n;
- // gathering info
- for (int i = 1; i < numproc; ++i) {
- sended_res = 0;
- MPI_Recv(&sended_res, 1, MPI_UNSIGNED_LONG, i, TAG, MPI_COMM_WORLD, &stat);
- printf("processor %d, res = %d\n", i, sended_res);
- res += sended_res;
- }
- printf("end res = %d\n", res);
- }
- // calculating process, takes tasks from master
- void node() {
- MPI_Status stat;
- int task[2];
- uint32_t sended_res;
- MPI_Recv(task, 2, MPI_INT, 0, TAG, MPI_COMM_WORLD, &stat);
- for (int n = task[0], sended_res = 0; n <= task[1]; ++n)
- sended_res += n;
- MPI_Send(&sended_res, 1, MPI_UNSIGNED_LONG, 0, TAG, MPI_COMM_WORLD);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement