Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // CPP Program to thread_solverply two matrix using pthreads
- #include <bits/stdc++.h>
- #include <chrono>
- using namespace std;
- using namespace std::chrono;
- // maximum size of matrix
- #define MAX 4
- // maximum number of threads
- #define MAX_THREAD 4
- int MX = 100;
- int **a, **b, **c;
- int core = 0;
- int n;
- pthread_t threads[MAX_THREAD];
- void print_array(int **a) {
- for (int i = 0; i < n; i++)
- {
- for (int j = 0; j < n; j++)
- {
- cout << a[i][j] << " ";
- }
- cout << endl;
- }
- }
- void* thread_solver(void* arg) {
- for (int i = n*core/4; i < (core+1)*n/4; i++)
- {
- for (int j = 0; j < n; j++)
- for (int k = 0; k < n; k++)
- c[i][j] += a[i][k] * b[k][j];
- }
- core++;
- }
- // Driver Code
- int main(int argc, char **argv)
- {
- time_t start, end;
- n = atoi(argv[1]);
- a = (int**)malloc(n*sizeof(int*));
- b = (int**)malloc(n*sizeof(int*));
- c = (int**)malloc(n*sizeof(int*));
- for (int i = 0; i < n; i++) {
- a[i] = (int*)malloc(n*sizeof(int));
- b[i] = (int*)malloc(n*sizeof(int));
- c[i] = (int*)malloc(n*sizeof(int));
- for (int j = 0; j < n; j++) {
- a[i][j] = rand() % MX;
- b[i][j] = rand() % MX;
- }
- }
- //cout << "A :" << endl;
- //print_array(a);
- //cout << endl;
- //cout << "B :" << endl;
- //print_array(b);
- //cout << endl;
- time(&start);
- clock_t st, ed;
- st = clock();
- clock_t tic = clock();
- auto strt = high_resolution_clock::now();
- for (int i = 0; i < MAX_THREAD; i++) {
- int* p;
- pthread_create(&threads[i], NULL, thread_solver, (void*)(p));
- }
- for (int i = 0; i < MAX_THREAD; i++)
- pthread_join(threads[i], NULL);
- //print_array(c);
- auto stop = high_resolution_clock::now() ;
- auto duration = duration_cast<microseconds>(stop - strt);
- clock_t toc = clock();
- ed = clock();
- time(&end);
- auto x =double(ed-st)/double(CLOCKS_PER_SEC);
- free(a);
- free(b);
- free(c);
- cout << "n : " << n << " time : " << duration.count() << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement