Advertisement
Guest User

Untitled

a guest
Mar 9th, 2019
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. #include<iostream>
  2. #include<cstdlib>
  3. #include <thread>
  4.  
  5. using namespace std;
  6.  
  7. // maximum size of matrix
  8. #define MAX 4
  9.  
  10. // maximum number of threads
  11. #define MAX_THREAD 4
  12.  
  13. int matA[MAX][MAX];
  14. int matB[MAX][MAX];
  15. int matC[MAX][MAX];
  16. int step_i = 0;
  17.  
  18. void* multi(void* arg)
  19. {
  20. int core = step_i++;
  21.  
  22.  
  23. for (int i = core * MAX / 4; i < (core + 1) * MAX / 4; i++)
  24. for (int j = 0; j < MAX; j++)
  25. for (int k = 0; k < MAX; k++)
  26. matC[i][j] += matA[i][k] * matB[k][j];
  27. }
  28.  
  29.  
  30. int main()
  31. {
  32.  
  33. for (int i = 0; i < MAX; i++) {
  34. for (int j = 0; j < MAX; j++) {
  35. matA[i][j] = rand() % 10;
  36. matB[i][j] = rand() % 10;
  37. }
  38. }
  39.  
  40.  
  41. cout << endl
  42. << "Matrix A" << endl;
  43. for (int i = 0; i < MAX; i++) {
  44. for (int j = 0; j < MAX; j++)
  45. cout << matA[i][j] << " ";
  46. cout << endl;
  47. }
  48.  
  49.  
  50. cout << endl
  51. << "Matrix B" << endl;
  52. for (int i = 0; i < MAX; i++) {
  53. for (int j = 0; j < MAX; j++)
  54. cout << matB[i][j] << " ";
  55. cout << endl;
  56. }
  57.  
  58. // declaring four threads
  59. thread(MAX_THREAD);
  60.  
  61.  
  62. // Creating four threads, each evaluating its own part
  63. for ( int i = 0; i < MAX_THREAD; i++) {
  64. thread[i] = thread(multi, i + 1);
  65.  
  66. }
  67.  
  68. // joining and waiting for all threads to complete
  69. for (int i = 0; i < MAX_THREAD; i++)
  70. join(thread[i],NULL);
  71.  
  72. // Displaying the result matrix
  73. cout << endl
  74. << "Multiplication of A and B" << endl;
  75. for (int i = 0; i < MAX; i++) {
  76. for (int j = 0; j < MAX; j++)
  77. cout << matC[i][j] << " ";
  78. cout << endl;
  79. }
  80. return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement