Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <mpi.h>
- using namespace std;
- typedef struct three_args_struct {
- int first;
- int second;
- double third;
- } triplet;
- void buildDerivedType(MPI_Datatype* mpi_triplet_type) {
- int nitems = 3;
- int block_lengths[3] = { 1, 1, 1 };
- MPI_Aint offsets[3];
- MPI_Datatype typelist[3] = { MPI_INT, MPI_INT, MPI_DOUBLE };
- offsets[0] = offsetof(triplet, first);
- offsets[1] = offsetof(triplet, second);
- offsets[2] = offsetof(triplet, third);
- MPI_Type_create_struct(nitems, block_lengths, offsets, typelist, mpi_triplet_type);
- MPI_Type_commit(mpi_triplet_type);
- }
- void initializeArray(triplet* arr, int size) {
- for (int i = 0; i < size; i++) {
- arr[i].first = i;
- arr[i].second = i * i;
- arr[i].third = i / 10.0;
- }
- }
- int main(int argc, char* argv[]) {
- MPI_Init(&argc, &argv);
- cout << "prj5.1" << endl;
- double startTime = MPI_Wtime();
- int rank;
- int threads_count;
- MPI_Status status;
- MPI_Comm_size(MPI_COMM_WORLD, &threads_count);
- MPI_Comm_rank(MPI_COMM_WORLD, &rank);
- int side_threads_count = threads_count - 1;
- if (threads_count < 2) {
- fprintf(stderr, "Requires at least two processes.\n");
- exit(-1);
- }
- triplet* buf = new triplet[threads_count];
- if (rank == 0) {
- initializeArray(buf, threads_count);
- for (int i = 0; i < threads_count; i++) {
- cout << i << ". first = " << buf[i].first << ", second = " << buf[i].second << ", third = " << buf[i].third << endl;
- }
- }
- MPI_Datatype* mpi_triplet_type = new MPI_Datatype;
- buildDerivedType(mpi_triplet_type);
- triplet* receivedInf = new triplet;
- MPI_Scatter(buf, 1, *mpi_triplet_type, receivedInf, 1, *mpi_triplet_type, 0, MPI_COMM_WORLD);
- int flag = 0;
- if (rank == 0) {
- flag = -1;
- MPI_Send(&flag, 1, MPI_INT, 1, 0, MPI_COMM_WORLD);
- }
- else {
- MPI_Recv(&flag, 1, MPI_INT, rank - 1, 0, MPI_COMM_WORLD, &status);
- cout << rank << ". Printing structure: first = " << receivedInf->first << ", second = " << receivedInf->second << ", third = " << receivedInf->third << endl;
- if (rank != threads_count - 1) {
- MPI_Send(&flag, 1, MPI_INT, rank + 1, 0, MPI_COMM_WORLD);
- }
- }
- double endTime = MPI_Wtime();
- double elapsed = endTime - startTime;
- cout << "Program runtime: " << elapsed << endl;
- MPI_Finalize();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement