Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // CPP Program to multiply two matrix using pthreads
- #include <bits/stdc++.h>
- using namespace std;
- // maximum size of matrix
- #define MAX 4
- // maximum number of threads
- #define MAX_THREAD 4
- int MX = 100;
- int **matA, **matB, **matC;
- int step_i = 0;
- int n;
- void* multi(void* arg)
- {
- int core = step_i++;
- // Each thread computes 1/4th of matrix multiplication
- for (int i = core * n / 4; i < (core + 1) * n / 4; i++)
- for (int j = 0; j < n; j++)
- for (int k = 0; k < n; k++)
- matC[i][j] += matA[i][k] * matB[k][j];
- }
- // Driver Code
- double job(int n)
- {
- time_t start, end;
- matA = (int**)malloc(n*sizeof(int*));
- matB = (int**)malloc(n*sizeof(int*));
- matC = (int**)malloc(n*sizeof(int*));
- for (int i = 0; i < n; i++) {
- matA[i] = (int*)malloc(n*sizeof(int));
- matB[i] = (int*)malloc(n*sizeof(int));
- matC[i] = (int*)malloc(n*sizeof(int));
- for (int j = 0; j < n; j++) {
- matA[i][j] = rand() % MX;
- matB[i][j] = rand() % MX;
- }
- }
- /** // Displaying matA
- cout << endl
- << "Matrix A" << endl;
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++)
- cout << matA[i][j] << " ";
- cout << endl;
- }
- // Displaying matB
- cout << endl
- << "Matrix B" << endl;
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++)
- cout << matB[i][j] << " ";
- cout << endl;
- }
- **/
- // declaring four threads
- pthread_t threads[MAX_THREAD];
- time(&start);
- clock_t st, ed;
- st = clock();
- clock_t tic = clock();
- // Creating four threads, each evaluating its own part
- for (int i = 0; i < MAX_THREAD; i++) {
- int* p;
- pthread_create(&threads[i], NULL, multi, (void*)(p));
- }
- // joining and waiting for all threads to complete
- for (int i = 0; i < MAX_THREAD; i++)
- pthread_join(threads[i], NULL);
- clock_t toc = clock();
- ed = clock();
- time(&end);
- auto x =double(ed-st)/double(CLOCKS_PER_SEC);
- return (double)(toc - tic) / CLOCKS_PER_SEC;
- // Displaying the result matrix
- /**
- cout << endl
- << "Multiplication of A and B" << endl;
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++)
- cout << matC[i][j] << " ";
- cout << endl;
- }
- **/
- }
- int main()
- {
- for (int i = 1; i < 55; i++)
- {
- cout << "n : " << i*i << ", time :" << job(i*i) << endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement