Advertisement
dark-Matter

parallel

Mar 7th, 2021
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.16 KB | None | 0 0
  1. // CPP Program to thread_solverply two matrix using pthreads
  2. #include <bits/stdc++.h>
  3. #include <chrono>
  4.  
  5. using namespace std;
  6. using namespace std::chrono;
  7. // maximum size of matrix
  8. #define MAX 4
  9.  
  10. // maximum number of threads
  11. #define MAX_THREAD 4
  12.  
  13.  
  14. int MX = 100;
  15. int **a, **b, **c;
  16. int core = 0;
  17. int n;
  18. pthread_t threads[MAX_THREAD];
  19.  
  20. void print_array(int **a) {
  21.     for (int i = 0; i < n; i++)
  22.     {
  23.         for (int j = 0; j < n; j++)
  24.         {
  25.             cout << a[i][j] << " ";
  26.         }
  27.         cout << endl;
  28.     }
  29.    
  30. }
  31.  
  32.  
  33. void* thread_solver(void* arg) {
  34.     for (int i = n*core/4; i < (core+1)*n/4; i++)
  35.     {
  36.         for (int j = 0; j < n; j++)
  37.             for (int k = 0; k < n; k++)
  38.                 c[i][j] += a[i][k] * b[k][j];
  39.     }
  40.     core++;
  41. }
  42.  
  43.  
  44. // Driver Code
  45. int main(int argc, char **argv)
  46. {
  47.     time_t start, end;
  48.     n = atoi(argv[1]);
  49.     a = (int**)malloc(n*sizeof(int*));
  50.     b = (int**)malloc(n*sizeof(int*));
  51.     c = (int**)malloc(n*sizeof(int*));
  52.  
  53.     for (int i = 0; i < n; i++) {
  54.         a[i] = (int*)malloc(n*sizeof(int));
  55.         b[i] = (int*)malloc(n*sizeof(int));
  56.         c[i] = (int*)malloc(n*sizeof(int));
  57.         for (int j = 0; j < n; j++) {
  58.             a[i][j] = rand() % MX;
  59.             b[i][j] = rand() % MX;
  60.         }
  61.     }  
  62.     //cout << "A :" << endl;
  63.     //print_array(a);
  64.     //cout << endl;
  65.     //cout << "B :" << endl;
  66.     //print_array(b);
  67.     //cout << endl;
  68.    
  69.  
  70.     time(&start);
  71.     clock_t st, ed;
  72.     st = clock();
  73.     clock_t tic = clock();
  74.     auto strt = high_resolution_clock::now();
  75.     for (int i = 0; i < MAX_THREAD; i++) {
  76.         int* p;
  77.         pthread_create(&threads[i], NULL, thread_solver, (void*)(p));
  78.     }
  79.  
  80.     for (int i = 0; i < MAX_THREAD; i++)
  81.         pthread_join(threads[i], NULL);
  82.  
  83.     //print_array(c);  
  84.     auto stop = high_resolution_clock::now() ;
  85.     auto duration = duration_cast<microseconds>(stop - strt);
  86.  
  87.     clock_t toc = clock();
  88.     ed = clock();
  89.     time(&end);
  90.     auto x =double(ed-st)/double(CLOCKS_PER_SEC);
  91.     free(a);
  92.     free(b);
  93.     free(c);
  94.     cout << "n : " << n << " time : " << duration.count() << endl;
  95.    
  96. }
  97.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement