Advertisement
Guest User

L5_Ex2_Pthread

a guest
Apr 23rd, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.65 KB | None | 0 0
  1. # include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <sys/time.h>
  5. #include <string.h>
  6. #include <math.h>
  7. #include <omp.h>
  8.  
  9. void *Exercitiul_2 (void *);
  10. int n = 1024;
  11. int p = 2;
  12. int mod = 0;
  13. int max_rep = 1;
  14. float **a, *b, *c;
  15.  
  16. int main(int argc, char *argv[]) {
  17.     int i, j, k, q, rep;
  18.     int* params;
  19.     pthread_t *ids;
  20.     struct timeval t1, t2; 
  21.     if (argc >= 2) n = atoi(argv[1]);
  22.     if (argc >= 3) p = atoi(argv[2]);
  23.     if (argc >= 4) mod = atoi(argv[3]);
  24.     if (argc >= 5) max_rep = atoi(argv[4]);
  25.     a = (float**)malloc(sizeof(float)*n);
  26.     b = (float*)malloc(sizeof(float)*n);
  27.     c = (float*)malloc(sizeof(float)*n);
  28.    
  29.     for (i = 0; i < n; i++)
  30.     {
  31.         a[i] = (float*)malloc(sizeof(float)*n);
  32.     }
  33.     for (i = 0; i < n; i++) {
  34.         b[i] = rand()/(float)RAND_MAX;
  35.         c[i] = 0;
  36.         for(j = 0; j < n; j++)
  37.         {
  38.             a[i][j] = rand()/(float)RAND_MAX;
  39.         }
  40.     }
  41.     params = (int*)malloc(sizeof(int)*p);
  42.     ids = (pthread_t*)malloc(sizeof(pthread_t)*p);
  43.     gettimeofday(&t1, NULL);
  44.     for (q = 0; q < p; q++)
  45.     {
  46.         params[q] = q;
  47.         pthread_create(&ids[q], 0, Exercitiul_2, (void*)&params[q]);
  48.     }
  49.     for (q = 0; q < p; q++)
  50.     {
  51.         pthread_join(ids[q], 0);
  52.     }
  53.    
  54.     gettimeofday(&t2, NULL);
  55.  
  56.     float tp = (t2.tv_sec - t1.tv_sec + 0.000001*(t2.tv_usec - t1.tv_usec));
  57.     for (i = 0; i < n; i++)
  58.         printf(" %f ", c[i]);
  59.     printf("\n");
  60.     printf("n=%d\np=%d\nTimp executie: %f\n", n, p, (float)tp);
  61.     return 0;
  62. }
  63.  
  64. void *Exercitiul_2(void *param)
  65. {
  66.     int i, j, k, first, last;
  67.     int q = *(int*)param;
  68.     int s = (int) n/p;
  69.     first = q*s;
  70.     last = first + s;
  71.     for (i = first; i < last; i++)
  72.         for(j = 0; j < n; j++)
  73.         {
  74.             c[i] += a[i][j]*b[j];
  75.         }
  76.     return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement