]> vgcfreebox.myrthtech.pt Git - ue-pp-squarematrixparallelisation.git/blobdiff - ParallelMatrixSearch.c
latex file
[ue-pp-squarematrixparallelisation.git] / ParallelMatrixSearch.c
index 2a3c49964e929ae079199b5346206172058aaf9b..949f0733912add777175d2b1db7dd9beade5d337 100644 (file)
@@ -9,6 +9,53 @@ const int m_cols = m_rows;
 _Atomic int hv = 0;
 int **matrix;
 
 _Atomic int hv = 0;
 int **matrix;
 
+typedef struct{
+  int start;
+  int end;
+} thread_args;
+
+void* parallel_search_cols(void *arg){
+  thread_args *args = (thread_args *)arg;
+  for(int r = 0; r < m_rows; r++){
+    for(int c = args->start; c < args->end; c++){
+      if(matrix[r][c] > hv){
+        hv = matrix[r][c];
+      }
+    }
+  }
+  return NULL;
+}
+
+void run_parallel_search(int num_threads) {
+    pthread_t *threads = malloc(num_threads * sizeof(pthread_t));
+    thread_args *args = malloc(num_threads * sizeof(thread_args));
+
+    if (threads == NULL || args == NULL) {
+        perror("Failed to allocate memory for threads");
+        exit(1);
+    }
+
+    int chunk_size = m_cols / num_threads;
+
+    for (int i = 0; i < num_threads; i++) {
+        args[i].start = i * chunk_size;
+        if (i == num_threads - 1) {
+            args[i].end = m_cols;
+        } else {
+            args[i].end = (i + 1) * chunk_size;
+        }
+        if (pthread_create(&threads[i], NULL, &parallel_search_cols, &args[i]) != 0) {
+            perror("Failed to create thread");
+            exit(1);
+        }
+    }
+
+    for (int i = 0; i < num_threads; i++) {
+        pthread_join(threads[i], NULL);
+    }
+    free(threads);
+    free(args);
+}
 
 int main(void){
   printf("1st --> Allocate memory\n");
 
 int main(void){
   printf("1st --> Allocate memory\n");
@@ -43,17 +90,11 @@ int main(void){
   t_t2 = clock() - t_t2;
   double t2_ttaken = ((double)t_t2)/CLOCKS_PER_SEC; 
   printf(" %f sec\n",t2_ttaken);  
   t_t2 = clock() - t_t2;
   double t2_ttaken = ((double)t_t2)/CLOCKS_PER_SEC; 
   printf(" %f sec\n",t2_ttaken);  
-
   
   printf("3rd --> Search matrix\n");
   clock_t t_t3; t_t3 = clock();
   
   printf("3rd --> Search matrix\n");
   clock_t t_t3; t_t3 = clock();
-  for(int r = 0; r < m_rows; r++){
-    for(int c = 0; c < m_cols; c++){
-      if(matrix[r][c] > hv){
-        hv = matrix[r][c];
-      }
-    }
-  }
+  int threads_to_use = 800;
+  run_parallel_search(threads_to_use);
   t_t3 = clock() - t_t3;
   double t3_ttaken = ((double)t_t3)/CLOCKS_PER_SEC;
   printf(" %f sec\n",t3_ttaken);
   t_t3 = clock() - t_t3;
   double t3_ttaken = ((double)t_t3)/CLOCKS_PER_SEC;
   printf(" %f sec\n",t3_ttaken);
@@ -63,5 +104,3 @@ int main(void){
   free(matrix);
   return 0;
 }
   free(matrix);
   return 0;
 }
-
-