// // Open Systems Laboratory // http://www.lam-mpi.org/tutorials/ // Indiana University // // MPI Tutorial // Homework: Manager/worker (calculate an average in parallel) // // Mail questions regarding tutorial material to lam at lam dash mpi dot org // #include #include using namespace std; int main(int argc, char *argv[]) { int source, dest; int total, workers; double avg; int *data, *sum, mysum; int rank, size; int i, len = 100, tag = 200; MPI::Request *request; MPI::Init(argc, argv); rank = MPI::COMM_WORLD.Get_rank(); size = MPI::COMM_WORLD.Get_size(); if (rank == 0) { // Allocate and initialize the data workers = size - 1; data = new int[workers * len]; sum = new int[workers]; request = new MPI::Request[workers]; for (i = 0; i < workers * len; ++i) data[i] = i; // Send the data to each of the other processes for (i = 0; i< workers; ++i) { int dest = i + 1; // Send the data to worker dest, use a non-blocking send and use // request[i] } // Wait for all of the sends to complete */ // Receive the results for (i = 0; i < workers; ++i) { int source = i + 1; // Do a non-blocking receive from source, placing the // incoming number in the sum array, again use request[i] } // Wait for all of the receives to complete total = 0; for (i = 0; i < workers; ++i) total += sum[i]; avg = total / (len * workers); cout << "The average is " << avg << endl; delete[] data; delete[] sum; delete[] request; } // Workers else { data = new int[100]; mysum = 0; // Receive the data from the manager for (i = 0; i < len; ++i) mysum += data[i]; // Send my sum back to the manager delete[] data; } MPI::Finalize(); return 0; }