40 likes | 117 Views
Parallel Programming in MPI Answer. January 18, 2012. 1. Sample answer of the last week's report. (1). int my_reduce(int *a, int *b, int c) { int i, p, myid, procs; int *t; MPI_Status st; MPI_Comm_rank(MPI_COMM_WORLD, &myid); MPI_Comm_size(MPI_COMM_WORLD, &procs);
E N D
Parallel Programming in MPIAnswer January 18, 2012 1
Sample answer of the last week's report. (1) int my_reduce(int *a, int *b, int c) { int i, p, myid, procs; int *t; MPI_Status st; MPI_Comm_rank(MPI_COMM_WORLD, &myid); MPI_Comm_size(MPI_COMM_WORLD, &procs); if (myid == 0){ t = (int *)malloc(c*sizeof(int)); MPI_Recv(t, c, MPI_INT, 1, 0, MPI_COMM_WORLD, &st); for (i = 0; i < N; i++) b[i] = a[i] + t[i]; for (p = 2; p < procs; p++){ MPI_Recv(t, c, MPI_INT, p, 0, MPI_COMM_WORLD, &st); for (i = 0; i < N; i++) b[i] += t[i]; } } else{ MPI_Send(a, c, MPI_INT, 0, 0, MPI_COMM_WORLD); } return 0; }
Sample answer of the last week's report. (2) int my_reduce(int *a, int *b, int c) { int i, mask, myid, procs, isfirst; int *t1, *t2; MPI_Status st; MPI_Comm_rank(MPI_COMM_WORLD, &myid); MPI_Comm_size(MPI_COMM_WORLD, &procs); mask = 1; isfirst = 1; t1 = (int *)malloc(c*sizeof(int)); if (myid == 0) t2 = b; else t2 = (int *)malloc(c*sizeof(int)); continue to the next page
Sample answer of the last week's report. (2) cont. while (mask < procs){ if (myid & mask){ if (mask == 1) MPI_Send(a, c, MPI_INT, myid-mask, 0, MPI_COMM_WORLD); else MPI_Send(t2, c, MPI_INT, myid-mask, 0, MPI_COMM_WORLD); break; } else{ MPI_Recv(t1, c, MPI_INT, myid+mask, 0, MPI_COMM_WORLD, &st); if (isfirst){ for (i=0; i<N; i++) t2[i] = a[i]+t1[i]; isfirst = 0; } else for (i=0; i<N; i++) t2[i] += t1[i]; mask <<= 1; } } free(t1); free(t2); return 0; }