]> vgcfreebox.myrthtech.pt Git - ue-pp-squarematrixparallelisation.git/blob - ParallelMatrixSearch.c
538af2481c9a069629d067ec0a02485210e5282d
[ue-pp-squarematrixparallelisation.git] / ParallelMatrixSearch.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <pthread.h>
4 #include <time.h>
5
6 const int m_rows = 40000;
7 const int m_cols = m_rows;
8
9 _Atomic int hv = 0;
10 int **matrix;
11
12 typedef struct{
13 int start;
14 int end;
15 } thread_args;
16
17 void* parallel_search_cols(void *arg){
18 thread_args *args = (thread_args *)arg;
19 for(int r = 0; r < m_rows; r++){
20 for(int c = args->start; c < args->end; c++){
21 if(matrix[r][c] > hv){
22 hv = matrix[r][c];
23 }
24 }
25 }
26 free(args);
27 return NULL;
28 }
29
30 int main(void){
31 printf("1st --> Allocate memory\n");
32 clock_t t_t1; t_t1 = clock();
33 size_t rows_size = m_rows * sizeof(int*);
34 matrix = malloc(rows_size);
35 if(matrix == NULL){
36 perror("malloc failled");
37 return 1;
38 }
39 size_t data_size = (size_t)m_rows * m_cols * sizeof(int);
40 int *data;
41 if(posix_memalign((void**)&data, 64, data_size) != 0){
42 perror("not able to alocate memory");
43 free(matrix);
44 return 1;
45 }
46 t_t1 = clock() - t_t1;
47 double t1_ttaken = ((double)t_t1)/CLOCKS_PER_SEC;
48 printf(" %f sec\n",t1_ttaken);
49
50 printf("2nd --> Populate the matrix\n");
51 clock_t t_t2; t_t2 = clock();
52 for(int r = 0; r<m_rows;r++){
53 matrix[r] = data + r * m_cols;
54 }
55 for(int r = 0; r < m_rows; r++){
56 for(int c = 0; c < m_cols; c++){
57 matrix[r][c] = r*m_cols+c;
58 }
59 }
60 t_t2 = clock() - t_t2;
61 double t2_ttaken = ((double)t_t2)/CLOCKS_PER_SEC;
62 printf(" %f sec\n",t2_ttaken);
63
64 printf("3rd --> Search matrix\n");
65 clock_t t_t3; t_t3 = clock();
66
67 pthread_t t1;
68 thread_args *args = malloc(sizeof(thread_args));
69 args->start = 0;
70 args->end = abs(m_cols/3);
71 pthread_create(&t1,NULL,&parallel_search_cols,args);
72
73 pthread_t t2;
74 thread_args *args2 = malloc(sizeof(thread_args));
75 args2->start = abs(m_cols/3);
76 args2->end = m_cols-(m_cols/3);
77 pthread_create(&t2,NULL,&parallel_search_cols,args2);
78
79 pthread_t t3;
80 thread_args *args3 = malloc(sizeof(thread_args));
81 args3->start = m_cols-abs((m_cols/3));
82 args3->end = m_cols;
83 pthread_create(&t3,NULL,&parallel_search_cols,args3);
84
85 pthread_join(t1,NULL);
86 pthread_join(t2,NULL);
87 pthread_join(t3,NULL);
88
89 t_t3 = clock() - t_t3;
90 double t3_ttaken = ((double)t_t3)/CLOCKS_PER_SEC;
91 printf(" %f sec\n",t3_ttaken);
92
93 printf("Done\n The biggest value found is %d", hv);
94 free(data);
95 free(matrix);
96 return 0;
97 }