集合通信
1.MPI_Reduce
将所进程的值归约到 root 进程, 得到一个结果
int MPI_Reduce(void * sendbuf, void * recvbuf, int count, MPI_Datatype datatype, MPI_Op op, int root, MPI_Comm comm)
void * sendbuf:发送数据的首地址
void * recvbuf:接受数据的首地址
int count:数据的大小
MPI_Datatype datatype:数据的类型
MPI_Op op:要进行的操作。MPI_SUM,MPI_MAX,…
int root:要归约到的进程。
MPI_Comm comm:通信域。在那些进程上进行该操作。MPI_COMM_WORLD表示在所有进程上进行该操作。
//将除0号进程的数组发送到0号进程中,并相加。
//MPI_Reduce函数:将所有进程的数据x根据指定的操作(如相加),然后将得到的结果放入到指定的进程中。
#include <iostream>
#include <mpi.h>
using std::cout;
using std::endl;
int main(int argc, char **argv)
{
int myid, procnum;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
MPI_Comm_size(MPI_COMM_WORLD, &procnum);
int num = 10;
double *x = new double[num];
double *z = new double[num];
for (int i = 0; i < num; i++)
{
if (myid == 0)
x[i] = 0;
else
x[i] = i;
}
MPI_Reduce(&x[0], &z[0], num, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
if (myid == 0)
for (int i = 0; i < num; i++)
cout << z[i] << " ";
delete[] x;
delete[] z;
MPI_Finalize();
return 0;
}
2.MPI_Allreduce
归约所有进程的计算结果, 并将最终的结果传递给所有其它的进程, 相当于每一个进程都执行了一次MPI_Reduce 调用。
int MPI_Allreduce(void * sendbuf, void * recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
void * sendbuf:发送数据的首地址
void * recvbuf:接受数据的首地址
int count:数据的大小
MPI_Datatype datatype:数据的类型
MPI_Op op:要进行的操作。MPI_SUM,MPI_MAX,…
MPI_Comm comm:通信域。在那些进程上进行该操作。MPI_COMM_WORLD表示在所有进程上进行该操作。
#include <iostream>
#include <mpi.h>
using std::cout;
using std::endl;
int main(int argc, char **argv)
{
int myid, procnum;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
MPI_Comm_size(MPI_COMM_WORLD, &procnum);
int num = 10;
double *x = new double[num];
double *z = new double[num];
for (int i = 0; i < num; i++)
{
if (myid == 0)
x[i] = 0;
else
x[i] = i;
}
MPI_Allreduce(&x[0],&z[0],num,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
if (myid == 0)
for (int i = 0; i < num; i++)
cout << z[i] << " ";
if (myid == 1)
for (int i = 0; i < num; i++)
cout << z[i] << " ";
delete[] x;
delete[] z;
MPI_Finalize();
return 0;
}