Skip to content

Instantly share code, notes, and snippets.

@keisukefukuda
Created July 12, 2015 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keisukefukuda/11cdda1207ff9987a8ca to your computer and use it in GitHub Desktop.
Save keisukefukuda/11cdda1207ff9987a8ca to your computer and use it in GitHub Desktop.
計算機システム MPIサンプル [4]
/*
* 計算機システム MPIサンプル [4]
* rank 0 のプロセスから、0以外のプロセスへ、配列を送信し、各プロセスは、データの各要素に自分のrankをかけ算し、
* その配列をrank 0へ送り返す
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <mpi.h>
#define LEN 5
void server(int size) {
int len = LEN * size;
int *buf = malloc(sizeof(int) * len);
int i, p;
/* データを初期化 */
for (i = 0; i < len; i++) {
buf[i] = i;
}
/* 処理前のデータを表示 */
for (i = 0; i < len; i++) {
printf("%d ", buf[i]);
}
printf("\n");
/* データを配る
* (0-LEN までの範囲は送受信されず、rank 0プロセスでローカルに処理されることに注意)
*/
for (p = 1; p < size; p++) {
MPI_Send(&buf[LEN*p], LEN, MPI_INT, p, 0, MPI_COMM_WORLD);
}
/* rank 0 自身の担当分の計算 */
for (i = 0; i < LEN; i++) {
buf[i] *= 0;
}
/* データを集める */
for (p = 1; p < size; p++) {
MPI_Status st;
MPI_Recv(&buf[LEN*p], LEN, MPI_INT, p, 0, MPI_COMM_WORLD, &st);
}
/* 処理後のデータを表示 */
for(i = 0; i < len; i++) {
printf("%d ", buf[i]);
}
printf("\n");
}
void client(int rank) {
int buf[LEN] = {0};
int i, err;
MPI_Status st;
/* データを受信 */
err = MPI_Recv(buf, LEN, MPI_INT, 0, 0, MPI_COMM_WORLD, &st);
assert(err == MPI_SUCCESS);
/* 配列の全要素ををrank倍 */
for (i = 0; i < LEN; i++) {
buf[i] *= rank;
}
/* データを送り返す */
err = MPI_Send(buf, LEN, MPI_INT, 0, 0, MPI_COMM_WORLD);
assert(err == MPI_SUCCESS);
}
int main(int argc, char **argv) {
int rank; /* 自分自身のプロセスID */
int size; /* 全体のプロセス数 */
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
assert(size > 1);
if (rank == 0) {
server(size);
} else {
client(rank);
}
MPI_Finalize();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment