什麼是MPI
MPI(Message Passing Interface)是消息傳遞函數庫的标準規範,支援C和Fortran,由衆多并行計算機廠商、軟體開發組織及并行應用機關共同維護的标準。
- MPI是一種标準或規範,不是特指某一個對它的具體實作。
- MPI是一種消息傳遞程式設計模型,并成為此模型的代表和事實上的标準,服務于程序通信
- MPI是一種庫描述,不是一種語言
- 由Fotran+MPI或C+MPI組成,有上百個函數調用接口,可直接調用
MPI程式的一些慣例——C 語言
- 必須包含頭檔案
"mpi.h"
- MPI函數傳回出錯代碼或
成功标志MPI_SUCCESS
- 字首為
,字首後第一個字母大寫,其餘字母全小寫,區分大小寫MPI_
MPI六大常用函數
1. 并行初始化
MPI_Init (int *argc,char ***argv)
2. 擷取程序總數
MPI_Comm_size (MPI_Comm comm,int *size)
3. 擷取目前程序号
MPI_Comm_rank (MPI_Comm comm,int *rank)
4. 發送消息
MPI_Send (void *buf,int count,MPI_Datatype datatype,int dest,int tag,MPI_Comm comm)
5. 接收消息
MPI_Recv (void *buf,int count,MPI_Datatype datatype,int source,int tag,MPI_Comm,MPI_Status *status)
6. 并行結束
MPI_Finalize()
簡單的發送和接收示例
- #include "mpi.h"
- #include <stdio.h>
- #include <string.h>
-
- void main(int argc,char* argv[])
- {
- int myid;
- char message[20];
- MPI_Status status;
- MPI_Init(&argc,&argv);
- MPI_Comm_rank(MPI_COMM_WORLD,&myid);
- if(myid == 0)
- {
- strcpy(message,"Hello process 1");
- MPI_Send(message,strlen(message),MPI_CHAR,1,99,MPI_COMM_WORLD);
- }
- else if(myid == 1)
- {
- MPI_Recv(message,20,MPI_CHAR,0,99,MPI_COMM_WORLD,&status);
- printf("Received:%s\n",message);
- }
- MPI_Finalize();
- }
執行結果:
- [[email protected] mpi]# mpirun -np 2 ./test-6-1
- Received:Hello process 1