Created
July 12, 2015 11:55
-
-
Save keisukefukuda/113a7c88beb1fda6cc1f to your computer and use it in GitHub Desktop.
算機システム MPIサンプル [5]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 計算機システム MPIサンプル [5] | |
* サンプル[4]の処理は、通信と受信を一発で行うAPIが用意されている | |
* ここでは MPI_Scatter と MPI_Gather の例を示す。 | |
* 実行結果は、サンプル[4]と全く同じになる. | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <assert.h> | |
#include <mpi.h> | |
#define LEN 5 | |
int main(int argc, char **argv) { | |
int rank; /* 自分自身のプロセスID */ | |
int size; /* 全体のプロセス数 */ | |
int *send_data = NULL, *recv_data = NULL; | |
int i, len; | |
MPI_Init(&argc, &argv); | |
MPI_Comm_rank(MPI_COMM_WORLD, &rank); | |
MPI_Comm_size(MPI_COMM_WORLD, &size); | |
assert(size > 1); | |
/* 領域確保、データを初期化、処理前のデータを表示 */ | |
if (rank == 0) { | |
send_data = malloc(sizeof(int) * LEN * size); | |
for (i = 0; i < size*LEN; i++) { | |
send_data[i] = i; | |
} | |
for (i = 0; i < size*LEN; i++) { | |
printf("%d ", send_data[i]); | |
} | |
printf("\n"); | |
} | |
recv_data = malloc(sizeof(int) * LEN); | |
/* MPI_Scatter : Rank 0 による MPI_Send, 全プロセスによる MPI_Recv を一回で行う */ | |
MPI_Scatter(send_data, LEN, MPI_INT, | |
recv_data, LEN, MPI_INT, | |
0, | |
MPI_COMM_WORLD); | |
/* 自分の担当分の計算 */ | |
for (i = 0; i < LEN; i++) { | |
recv_data[i] *= rank; | |
} | |
/* MPI_Gather : Rank 0 による MPI_Recv, 全プロセスによる MPI_Send を一回で行う */ | |
MPI_Gather(recv_data, LEN, MPI_INT, | |
send_data, LEN, MPI_INT, | |
0, MPI_COMM_WORLD); | |
if (rank == 0) { | |
/* 処理後のデータを表示 */ | |
for(i = 0; i < size*LEN; i++) { | |
printf("%d ", send_data[i]); | |
} | |
printf("\n"); | |
} | |
MPI_Finalize(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment