[并行程序设计][MPI]5个核并行输出“I love you !!!”

mpicc ./文件名.c -o 文件名.o
mpirun -n 5 ./文件名.o

#include 
#include 
#include 

#define MAX 100

int main(int argc,char* argv[]){
	
	//mpi initialize
	MPI_Init(NULL,NULL);
	
	//the rank of process which is in communicator
	int process_rank = 0;
	
	//the number of processes belonging to communicator
	int comm_size = 0;
	
	
	//get the communicator size
	MPI_Comm_size(MPI_COMM_WORLD,&comm_size);
	
	//get the process rank 
	MPI_Comm_rank(MPI_COMM_WORLD,&process_rank);
	
	//initialize a array with type of char to be a buffer storing string
	char str[MAX] = {'\0'};
	
	//A dictionary 
	char abc[4][5]={"I","love","you","!!!"};
	
	//arrange processes to do my job
	if(process_rank!=0){//this process must be the subordinate process
		
		//put the string into str
		sprintf(str,"I am %d of %d:\t%s",process_rank,comm_size,abc[process_rank-1]);
		
		//send str to process 0
		MPI_Send(str,strlen(str)+1,MPI_CHAR,0,0,MPI_COMM_WORLD);
	
	}else{//this process must be the major process
		
		printf("i am the process %d\n",process_rank);

		int i = 0;
		for(i=1;i<comm_size;i++){
			//receive message from process i ,and store it into str
			MPI_Recv(str,MAX,MPI_CHAR,i,MPI_ANY_TAG,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
			
			//and print what we just received  
			printf("%s\n",str);
		}
	}
	
	//free MPI
	MPI_Finalize();	
} 

你可能感兴趣的:(并行程序设计)