MPI_IN_PLACE
用在 MPI_GATHER
、MPI_Reduce
等有 send_buf
和 recv_buf
的函數中,用來代替 send_buf
,說明當前進程既發送又接受數據,而且要發送的數據和在要接收的數據的保存在同一內存。
① MPI_Gather 的例子:
int *array = new int[4];
memset(array, 0, sizeof(int)* 4);
array[world_rank] = world_rank + 1;
if (world_rank != 0)
{
MPI_Gather(array + world_rank, 1, MPI_INT, array, 1, MPI_INT,0, MPI_COMM_WORLD);
} else
{
MPI_Gather(MPI_IN_PLACE, 1, MPI_INT, array, 1, MPI_INT, 0, MPI_COMM_WORLD);
}
array 最後爲 {1,2,3,4},由於接收進程爲 0 號,所以也只有 0 號進程可以用 MPI_IN_PLACE
代替 send_buf
。
② MPI_Reduce 的例子:
int send_data = world_rank;
if (world_rank != 0)
{
MPI_Reduce(&send_data, &send_data, 1, MPI_INT, MPI_MAX, 0, MPI_COMM_WORLD);
} else
{
MPI_Reduce(MPI_IN_PLACE, &send_data, 1, MPI_INT, MPI_MAX, 0, MPI_COMM_WORLD);
}
if (world_rank == 0)
{
printf("%d\n", send_data);
}
進程 0 中 send_data 最後爲 3。因爲進程 0 發送的數據也是 send_data,所以也只有 0 號進程可以用 MPI_IN_PLACE
代替 send_buf
。
注意,在不滿足使用場景的進程中使用 MPI_IN_PLACE 時(比如上面兩個例子的非 0 進程),會拋異常。