Advertisement
dark-Matter

vyom_lawda

Mar 7th, 2021
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. // CPP Program to multiply two matrix using pthreads
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // maximum size of matrix
  6. #define MAX 4
  7.  
  8. // maximum number of threads
  9. #define MAX_THREAD 4
  10.  
  11.  
  12. int MX = 100;
  13.  
  14. int **matA, **matB, **matC;
  15.  
  16. int step_i = 0;
  17. int n;
  18.  
  19. void* multi(void* arg)
  20. {
  21.     int cr = step_i++;
  22.  
  23.     // Each thread computes 1/4th of matrix multiplication
  24.     for (int i = cr * n / 4; i < (cr + 1) * n / 4; i++)
  25.         for (int j = 0; j < n; j++)
  26.             for (int k = 0; k < n; k++)
  27.                 matC[i][j] += matA[i][k] * matB[k][j];
  28. }
  29.  
  30.  
  31. // Driver Code
  32. int main()
  33. {
  34.     time_t start, end;
  35.     cin >> n;
  36.     matA = (int**)malloc(n*sizeof(int*));
  37.     matB = (int**)malloc(n*sizeof(int*));
  38.     matC = (int**)malloc(n*sizeof(int*));
  39.  
  40.     for (int i = 0; i < n; i++) {
  41.         matA[i] = (int*)malloc(n*sizeof(int));
  42.         matB[i] = (int*)malloc(n*sizeof(int));
  43.         matC[i] = (int*)malloc(n*sizeof(int));
  44.         for (int j = 0; j < n; j++) {
  45.             matA[i][j] = rand() % MX;
  46.             matB[i][j] = rand() % MX;
  47.         }
  48.     }  
  49.     pthread_t threads[MAX_THREAD];
  50.  
  51.     time(&start);
  52.     clock_t st, ed;
  53.     st = clock();
  54.     clock_t tic = clock();
  55.     for (int i = 0; i < MAX_THREAD; i++) {
  56.         int* p;
  57.         pthread_create(&threads[i], NULL, multi, (void*)(p));
  58.     }
  59.  
  60.     for (int i = 0; i < MAX_THREAD; i++)
  61.         pthread_join(threads[i], NULL);  
  62.     clock_t toc = clock();
  63.     ed = clock();
  64.     time(&end);
  65.     auto x =double(ed-st)/double(CLOCKS_PER_SEC);
  66.     free(matA);
  67.     free(matB);
  68.     free(matC);
  69.     cout << "n : " << n << " time:" <<(double)(toc - tic) / CLOCKS_PER_SEC << endl;
  70.    
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement