MPI(消息傳遞藉口), 直接上 哈羅世界
#include <stdio.h>
#include <string.h>
#include <mpi.h> // mpi頭文件
const int Max_string = 100;
int main(){
char greetings[Max_string];
int comm_sz; // 進程數
int my_rank; // 當前進程編號
MPI_Init(NULL,NULL) /* MPI_Init(int*,char**) 大部分情況下可以不填 */
/* 通信子是一組可以互相發送消息的進程集合,下面兩句話的意思是用戶啓動程序時,定義由用戶啓動的所有進程所組成的通信子,
這個通信子偉 MPI_COMM_WORLD */
// 第一個參數爲通信子,類型爲 MPI_COMM , 第二個參數分別爲進程數量和進程號 , 進程號從0開始。
MPI_Comm_size(MPI_COMM_WORLD,&comm_sz);
MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
/* 當進程號不爲0時發送數據*/
if (my_rand != 0)
{
//字符串寫入greetings
sprintf(greetings,"Greetings from process %d of %d",my_rank,comm_sz);
//發送API 參數爲: /void* msg_bu_p / int msg_size/ MPI_Datatype msg_type / int dest/ int tag/ MPI_Comm communicator/
MPI_Send(greetings,strlen(greetings)+1,MPI_CHAR,0,0,MPI_COMM_WORLD);
}
/* 進程號爲0時接受數據 */
else{
printf("Greetings from process %d of %d\n",my_rank,comm_sz);
for (int i = 0; i < comm_sz; ++i)
{
MPI_Recv(greetings,Max_string,MPI_CHAR,i,0,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
printf("%s\n",greetings);
}
}
MPI_Finalize();
return 0;
}