By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,089 Members | 2,254 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,089 IT Pros & Developers. It's quick & easy.

How to multiply matrices using threads

P: 1
In my main program i am filling 2 matrices mata and matb. Then I'm multiplying them in my thread function to get matc. However, i am getting segmentation falults

Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2. #include<pthread.h>
  3.  
  4.     int mata[18][16];
  5.     int matb[16][18];
  6.     int matc[18][18];
  7.  
  8. void* compute_c_ij(void* arg)
  9. {
  10.     int k;
  11.     int n= *((int*)arg);
  12.  
  13.     for(k=0;k<16;++k)
  14.     {
  15.         matc[n][n] += mata[n][k] + matb[k][n];
  16.     }
  17.  
  18.         pthread_exit(NULL);
  19. }
  20.  
  21. int main()
  22. {
  23.  
  24.     pthread_t thr[18];
  25.  
  26.  
  27.     int n,m;
  28.  
  29.     int i,j;
  30.  
  31.     for(i=0;i<18;++i)
  32.         for(j=0;j<16;++j)
  33.             {
  34.             mata[i][j] = (i+1) +(j+1);
  35.             }
  36.  
  37.     for (i=0; i<16; ++i)
  38.         for(j=0;j<18;++j)
  39.             {
  40.             matb[i][j]= (i+1)+(2*(j+1));
  41.             }
  42.  
  43.  
  44.     for (i=0;i<18 ; ++i)
  45.      {
  46.      pthread_create(&thr[i],NULL,compute_c_ij,NULL);
  47.      }
  48.  
  49.      for (i=0 ; i<18 ; ++i)
  50.      {
  51.       pthread_join(thr[i],NULL);
  52.       printf("%d\n",matc[i][i]);
  53.      }
  54.  
  55.      pthread_exit(NULL);
  56. }
  57.  
  58.  
  59.  
  60.  
  61.  
Feb 14 '12 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
There is no way in C or C++ that you know the side of an array from just the address of the array. You need arguments for the number of elements in each dimension:
Expand|Select|Wrap|Line Numbers
  1. void* compute_c_ij(void* arg)
  2.  9. {
  3.  10.     int k;
  4.  11.     int n= *((int*)arg);   <<<<<<< this can be outside your array
  5.  12. 
  6.  13.     for(k=0;k<16;++k)
  7.  14.     {
  8.  15.         matc[n][n] += mata[n][k] + matb[k][n];
  9.  
Plus this code won't work for arrays with a second dimension greater than 16.
Feb 15 '12 #2

Post your reply

Sign in to post your reply or Sign up for a free account.