歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> MPI 並行解上三角矩陣表示的方程組

MPI 並行解上三角矩陣表示的方程組

日期:2017/3/1 10:13:29   编辑:Linux編程

MPI最基本的回代法實現

  1. #include "mpi.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #define ROOT 0
  5. #define TAG 0
  6. int main(int argc,char *argv[]) {
  7. float matrix[][4]={{2,3,4,5},//the upper trangular matrix representing a equation set
  8. {0,2,3,4},
  9. {0,0,2,3}};
  10. int xcnt=3;//cout of x
  11. int self,size,tag=0;
  12. MPI_Init(&argc,&argv);
  13. MPI_Comm_rank(MPI_COMM_WORLD,&self);
  14. MPI_Comm_size(MPI_COMM_WORLD,&size);
  15. MPI_Request r;
  16. MPI_Status s;
  17. MPI_Datatype MPI_VEC;
  18. MPI_Type_vector(xcnt+1,1,1,MPI_FLOAT,&MPI_VEC);
  19. MPI_Type_commit(&MPI_VEC);
  20. float* equation=(float*)malloc((xcnt+1)*sizeof(float));
  21. float xs,xr;
  22. if(0==self) {//send each process the correspond equation
  23. //parellel send and copy
  24. MPI_Issend(matrix[1],1,MPI_VEC,1,TAG,MPI_COMM_WORLD,&r);
  25. for(int i=0;i<=xcnt;++i) {
  26. equation[i]=matrix[0][i];
  27. }
  28. MPI_Wait(&r,&s);
  29. for(int i=2;i<size;++i) {
  30. MPI_Ssend(matrix[i],1,MPI_VEC,i,TAG,MPI_COMM_WORLD);
  31. }
  32. } else {
  33. MPI_Recv(equation,1,MPI_VEC,ROOT,TAG,MPI_COMM_WORLD,&s);
  34. }
  35. for(int i=xcnt-1;i>=0;--i) {
  36. if(i==self) {
  37. xs=equation[xcnt]/equation[i];
  38. printf("x%d = %f \n",self,xs);
  39. MPI_Bcast(&xs,1,MPI_FLOAT,i,MPI_COMM_WORLD);
  40. } else {
  41. MPI_Bcast(&xs,1,MPI_FLOAT,i,MPI_COMM_WORLD);
  42. if(i>self) {
  43. equation[xcnt]-=equation[i]*xs;
  44. }
  45. }
  46. }
  47. free(equation);
  48. MPI_Finalize();
  49. return 0;
  50. }
Copyright © Linux教程網 All Rights Reserved