Advertisement
bkit4s0

[lab3_1.c XLSS] ver 1

Mar 6th, 2015
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.95 KB | None | 0 0
  1. #include "mpi.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #define ARRAYSIZE 1000
  5. #define MASTER 0
  6.  
  7. int data1[ARRAYSIZE];
  8. int data2[ARRAYSIZE];
  9.  
  10. int update(int,int,int);
  11. int main(int argc, char *argv[]) {
  12.     int numtasks, mysum, offset, source,dest, taskid, chunksize, rc,i;
  13.     MPI_Status status;
  14.  
  15.     MPI_Init(&argc,&argv);
  16.     MPI_Comm_size(MPI_COMM_WORLD,&numtasks);
  17.     MPI_Comm_rank(MPI_COMM_WORLD,&taskid);
  18.     chunksize = ARRAYSIZE/numtasks;
  19.  
  20.     if(taskid==MASTER) {
  21.         // Init vetor
  22.         for (i = 0; i < ARRAYSIZE; ++i) {
  23.             data1[i]=i;
  24.             data2[i]=i;
  25.         }
  26.         /* Send each task its portion of the array - master keeps 1st part */
  27.         offset = chunksize;
  28.         for (i = 0; i < numtasks; ++i) {
  29.             MPI_Send(&offset,1,MPI_INT,dest,j,MPI_COMM_WORLD);
  30.             MPI_Send(&data1[offset],1,MPI_INT,dest,j,MPI_COMM_WORLD);
  31.             MPI_Send(&data2[offset],1,MPI_INT,dest,j,MPI_COMM_WORLD);
  32.             offset+=offset+chunksize;
  33.         }
  34.         /* Master does its part of the work */
  35.         offset = 0;
  36.         mysum = update(offset, chunksize, taskid);
  37.  
  38.         /* Wait to receive results from each task */
  39.         for (i = 0; i < numtasks; ++i) {
  40.             source = i;
  41.             MPI_Recv(&offset, 1, MPI_INT, source, NULL, MPI_COMM_WORLD, &status);
  42.         }
  43.         printf("*** Final sum= %d ***\n",sum);
  44.     }   /* end of master section */
  45.     if (taskid > MASTER) {
  46.           /* Receive my portion of array from the master task */
  47.           source = MASTER;
  48.           MPI_Recv(&offset, 1, MPI_INT, source, NULL, MPI_COMM_WORLD, &status);
  49.           MPI_Recv(&data[offset], chunksize, MPI_FLOAT, source, NULL,
  50.             MPI_COMM_WORLD, &status);
  51.  
  52.           mysum = update(offset, chunksize, taskid);
  53.  
  54.           /* Send my results back to the master task */
  55.           dest = MASTER;
  56.           MPI_Send(&mysum, 1, MPI_INT, dest, NULL, MPI_COMM_WORLD);
  57.     } /* end of non-master */
  58.  
  59.     return 0;
  60. }
  61. int update(int offset,int chunk, int taskid) {
  62.     int i;
  63.     int mysum = 0;
  64.     for (i = offset; i < offset+ chunk; ++i)
  65.     {
  66.         mysum+=data1[i]*data2[i];
  67.     }
  68.     printf("Task %d mysum = %d\n",myid,mysum);
  69.     return mysum;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement