您的位置:首页 > 其它

MPI学习-MPI_Bcast and MPI_Scatter

2015-11-25 13:04 721 查看
MPI_Bcast:

distribute to all processes witnin the communicator an identical piece of data.



Function Call Syntax:

int MPI_Bcast(void *buffer,  /*starting address of the send buffer*/
int count,  /*number of elements in the send buffer*/
MPI_Datatype datatype,
int root,  /*rank of the process brocasting its data*/
MPI_Common comm);


example1:

/**
* MPI_Bcast.
*/
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#define N 3

int main(int argc, char *argv[])
{
int i, myrank, nprocs;
int *buffer;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);

// 所有进程都开辟大小为N的整型内存空间.
buffer = new int
;
for (i = 0; i < N; i++)
{
buffer[i] = myrank+i;
printf("before bcasting, myrank = %d, buffer[%d] = %d\n",
myrank, i, buffer[i]);

}
printf("\n");

// 以进程0作为根进程将buffer广播给所有其它进程.
MPI_Bcast(buffer, N, MPI_INT, 0, MPI_COMM_WORLD);

for (i = 0; i < N; i++)
printf("after bcasting, myrank = %d, buffer[%d] = %d\n",
myrank, i, buffer[i]);
printf("\n");
free(buffer);
MPI_Finalize();
return 0;
}


output when number of processes is 2:



MPI_Scatter:



Function Call Syntax:

int MPI_Scatter(void *send˙buf,
int send_count,/*recv_count*tatalnodes*/
MPI_Datatype send_type,
void *recv_buf,
int recv_count,/*number of elements for any single receive*/
MPI_Datatype recv_type,
int root,/*rank of the process sending data*/
MPI_Common comm);


example2:

/*MPI_Scatter*/

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>

#define N 1

int main(int argc, char *argv[])
{
int i, myrank, nprocs;
int *send_buffer;
int *recv_buffer;

MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);

recv_buffer = new int
;
send_buffer = new int[nprocs * N];
if (myrank == 0)
{
for (i = 0; i < nprocs * N; i++)
{
send_buffer[i] = i + 10;
printf("myrank = %d, send_buffer[%d] = %d\n", myrank, i, send_buffer[i]);
}
printf("\n");
}
MPI_Scatter(send_buffer, N, MPI_INT,
recv_buffer, N, MPI_INT,0, MPI_COMM_WORLD);

for (i = 0; i < N; i++)
{
printf("myrank = %d, recv_buffer[%d] = %d\n", myrank, i, recv_buffer[i]);
}

delete[]recv_buffer;
delete[] send_buffer;
MPI_Finalize();
return 0;
}


output when number of processes is 4:



#include <iostream>
using namespace std;

// 函数声明,
int getArea(int width,int height);

int main() {
int width,height,area;
cout<<"width:";
// 接受参数
cin>>width;
cout<<"height:";
cin>>height;
// 调用函数
area = getArea(width, height);
// 打印输出
cout<<"area:"<<area<<"\n";
}

// 函数定义
int getArea(int width,int height) {
return width * height;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: