Goal: 有一个vector, 对每个元素进行一个除法操作,然后将结果再收集到主结点。
直接上程序:
#include"stdafx.h"
#include"mpi.h"
#include"stdio.h"
#include"stdlib.h"
#include<iostream>
#define N 20
using namespace std;
int main(int argc,char* argv[])
{
int rank, size; // name of process, number of process
int *sendcounts; // array indicating how many elements will be sent from root
int *displs; // array indicating the displacements where each segment begins
double Array[N]; // data need to be sent
for(int i=0;i<N;i++)Array[i] = i; //initialize data
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
sendcounts = (int*)malloc(sizeof(int)*size);
displs = (int*)malloc(sizeof(int)*size);
int sum = 0; // Sum of distributed elements, can be used to calculate displacements for each segment
double rec_buf[100]; // buffer where the received data should be saved for each process
// Step 1: calculate send counts and displacements
for (int i = 0; i < size; i++) {
sendcounts[i] = N/size;
if(i==0)sendcounts[i] += N%size;
displs[i] = sum;
sum += sendcounts[i];
}
// output sendcounts and displacement for each process at root rank
if (0 == rank) {
for (int i = 0; i < size; i++) {
std::cout<<"Rank: "<<i<<" sendcounts: "<<sendcounts[i]<<" displacement: "<<displs[i]<<std::endl;}
}
// scatter the data among processes
MPI_Scatterv(&Array, sendcounts, displs, MPI_DOUBLE, &rec_buf, 100, MPI_DOUBLE, 0, MPI_COMM_WORLD);
// output received data for each process
std::cout<<"Rank= "<<rank<<" Received: ";
for (int i = 0; i < sendcounts[rank]; i++) {
std::cout<<rec_buf[i]<<'\t';}
std::cout<<std::endl;
MPI_Finalize();
free(sendcounts);
free(displs);
return 0;
}
如果把double array 换成vector, 则代码基本类似,只需要做如下修改:
std::vector<double> Array; // data need to be sent
for(int i=0;i<N;i++)Array.push_back(i); //initialize data
。。。。。
MPI_Scatterv(&Array.front(), sendcounts, displs, MPI_DOUBLE, &rec_buf, 100, MPI_DOUBLE, 0, MPI_COMM_WORLD);
接下来的问题是如果vector中的元素是class,如何传递的问题-boost mpi