Advertisement
Armaritto

Untitled

Mar 17th, 2024
18
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.89 KB | None | 0 0
  1. void aThreadPerElement(int rowA, int colA, int rowB, int colB, int** a, int** b){
  2.     if (colA != rowB) {
  3.         printf("Matrices cannot be multiplied: Incompatible dimensions.\n");
  4.         return;
  5.     }
  6.     struct timeval stop, start;
  7.     int** c = malloc(rowA * sizeof(int*));
  8.     for(int i = 0; i < rowA; i++){
  9.         c[i] = malloc(colB * sizeof(int));
  10.     }
  11.     pthread_t threads[rowA][colB];
  12.     int rc;
  13.     gettimeofday(&start, NULL);
  14.     for (int i = 0; i < rowA; i++) {
  15.         for (int j = 0; j < colB; j++) {
  16.             c[i][j] = 0;
  17.             struct thread_data *tdata = malloc(sizeof(struct thread_data));
  18.             tdata->a =  a;
  19.             tdata->b =  b;
  20.             tdata->c =  c;
  21.             tdata->colA = colA;
  22.             tdata->colB = colB;
  23.             tdata->rowA = rowA;
  24.             tdata->rowB = rowB;
  25.             tdata->i = i;
  26.             tdata->j = j;
  27.             rc = pthread_create(&threads[i][j], NULL,  n, (void*)tdata);
  28.             if(rc){
  29.                 printf("ERROR; return code from pthread_create() is %d\n", rc);
  30.                 exit(-1);
  31.             }
  32.         }
  33.     }
  34.     gettimeofday(&stop, NULL);
  35.     for(int i = 0 ; i < rowA ; ++i){
  36.         for(int j = 0 ; j < colB ; ++j) {
  37.             pthread_join(threads[i][j], NULL);
  38.         }
  39.     }
  40.     printf(RED "Multiplication Finished you can see results in c.txt\n" );
  41.     printf("Seconds taken %lu\n", stop.tv_sec - start.tv_sec);
  42.     printf("Microseconds taken: %lu\n", stop.tv_usec - start.tv_usec);
  43.     printf(RESET);
  44.     FILE *fp;
  45.     fp = fopen("c.txt", "w");
  46.     if (fp == NULL) {
  47.         printf("File not found\n");
  48.         return;
  49.     }
  50.     fprintf(fp, "row=%d col=%d\n", rowA, colB);
  51.     for (int i = 0; i < rowA; i++) {
  52.         for (int j = 0; j < colB; j++) {
  53.             fprintf(fp, "%d ", c[i][j]);
  54.         }
  55.         fprintf(fp, "\n");
  56.     }
  57.     fclose(fp);
  58.     free(c);
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement