Advertisement
Guest User

Untitled

a guest
Mar 9th, 2019
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. #include<iostream>
  2. #include<cstdlib>
  3. #include <thread>
  4. #include<windows.h>
  5. using namespace std;
  6.  
  7. // maximum size of matrix
  8. static const long MAX = 4;
  9.  
  10. // maximum number of threads
  11. static const int 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. std::thread threads[MAX_THREAD];
  60.  
  61.  
  62. // Creating four threads, each evaluating its own part
  63. for (int i = 0; i < MAX_THREAD; i++) {
  64.  
  65. int* p;
  66. threads[i] = std::thread(multi, std::ref(*p), i);
  67.  
  68. }
  69.  
  70. // joining and waiting for all threads to complete
  71. for (int i = 0; i < MAX_THREAD; i++)
  72. threads[i].join();
  73. // Displaying the result matrix
  74. cout << endl
  75. << "Multiplication of A and B" << endl;
  76. for (int i = 0; i < MAX; i++) {
  77. for (int j = 0; j < MAX; j++)
  78. cout << matC[i][j] << " ";
  79. cout << endl;
  80. }
  81.  
  82.  
  83. system("pause");
  84. return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement