Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<cstdlib>
- #include <thread>
- #include<windows.h>
- using namespace std;
- // maximum size of matrix
- static const long MAX = 4;
- // maximum number of threads
- static const int MAX_THREAD = 4;
- int matA[MAX][MAX];
- int matB[MAX][MAX];
- int matC[MAX][MAX];
- int step_i = 0;
- void* multi(void* arg)
- {
- int core = step_i++;
- for (int i = core * MAX / 4; i < (core + 1) * MAX / 4; i++)
- for (int j = 0; j < MAX; j++)
- for (int k = 0; k < MAX; k++)
- matC[i][j] += matA[i][k] * matB[k][j];
- }
- int main()
- {
- for (int i = 0; i < MAX; i++) {
- for (int j = 0; j < MAX; j++) {
- matA[i][j] = rand() % 10;
- matB[i][j] = rand() % 10;
- }
- }
- cout << endl
- << "Matrix A" << endl;
- for (int i = 0; i < MAX; i++) {
- for (int j = 0; j < MAX; j++)
- cout << matA[i][j] << " ";
- cout << endl;
- }
- cout << endl
- << "Matrix B" << endl;
- for (int i = 0; i < MAX; i++) {
- for (int j = 0; j < MAX; j++)
- cout << matB[i][j] << " ";
- cout << endl;
- }
- // declaring four threads
- std::thread threads[MAX_THREAD];
- // Creating four threads, each evaluating its own part
- for (int i = 0; i < MAX_THREAD; i++) {
- int* p;
- threads[i] = std::thread(multi, std::ref(*p), i);
- }
- // joining and waiting for all threads to complete
- for (int i = 0; i < MAX_THREAD; i++)
- threads[i].join();
- // Displaying the result matrix
- cout << endl
- << "Multiplication of A and B" << endl;
- for (int i = 0; i < MAX; i++) {
- for (int j = 0; j < MAX; j++)
- cout << matC[i][j] << " ";
- cout << endl;
- }
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement