Skip to content

Instantly share code, notes, and snippets.

@printesoi
Created November 26, 2012 23:02
Show Gist options
  • Save printesoi/4151250 to your computer and use it in GitHub Desktop.
Save printesoi/4151250 to your computer and use it in GitHub Desktop.
Distributed sort in MPI
/*
* ===========================================================================
*
* Filename: sort.cpp
* Author: Dodon Victor, dodonvictor AT gmail DOT com
* Created: 11/22/2012 04:32:15 PM
* Editor: Vim 7.3
* Compiler: clang 3.2
* OS: Archlinux x86_64
*
* Description: Sortare paralela in MPI
*
* ===========================================================================
*/
#include <mpi.h>
#include <iostream>
int values[] = {5, 3, 8, 1, 9, 4, 2, 6, 7, 0};
int n = 10;
int sortedValues[10];
int main(int argc, char *argv[])
{
int nthreads, rank;
int tag = 1;
MPI::Init(argc, argv);
MPI::COMM_WORLD.Set_errhandler(MPI::ERRORS_THROW_EXCEPTIONS);
try {
nthreads = MPI::COMM_WORLD.Get_size();
rank = MPI::COMM_WORLD.Get_rank();
if (rank == 0)
{
std::cout << "Initial values: ";
for (int i = 0; i < n; ++i)
{
std::cout << values[i] << " ";
}
std::cout << std::endl;
}
int current;
int root = 0;
MPI::COMM_WORLD.Scatter(values, 1, MPI::INT, &current, 1, MPI::INT, root);
for (int i = 0; i < n; ++i)
{
if ((i % 2 == 0 && rank % 2 == 0) || (i % 2 && rank % 2))
{
if (rank < nthreads - 1)
{
MPI::COMM_WORLD.Send(&current, 1, MPI::INT, rank + 1, tag);
MPI::COMM_WORLD.Recv(&current, 1, MPI::INT, rank + 1, tag);
}
}
else
{
if (rank > 0) {
int recVal;
MPI::COMM_WORLD.Recv(&recVal, 1, MPI::INT, rank - 1, tag);
if (recVal > current) {
int tmp = current;
current = recVal;
recVal = tmp;
}
MPI::COMM_WORLD.Send(&recVal, 1, MPI::INT, rank - 1, tag);
}
}
MPI::COMM_WORLD.Barrier();
}
MPI::COMM_WORLD.Gather(&current, 1, MPI::INT, sortedValues, 1, MPI::INT, root);
if (rank == 0)
{
std::cout << "Sorted values: ";
for (int i = 0; i < n; ++i)
{
std::cout << sortedValues[i] << " ";
}
std::cout << std::endl;
}
} catch (MPI::Exception e) {
std::cout << "MPI exception: " << e.Get_error_code() << " - " << e.Get_error_string() << std::endl;
}
MPI::Finalize();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment