Advertisement
salmaNAS

mat

Nov 22nd, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. // C Program to multiply two matrix using pthreads without
  2. // use of global variables
  3. #include<stdio.h>
  4. #include<pthread.h>
  5. #include<unistd.h>
  6. #include<stdlib.h>
  7. #define MAX 2
  8.  
  9.  
  10. //Each thread computes single element in the resultant matrix
  11. void *mult(void* arg)
  12. {
  13. int *data = (int *)arg;
  14. int k = 0, i = 0;
  15.  
  16. int x = data[0];
  17. for (i = 1; i <= x; i++)
  18. k += data[i]*data[i+x];
  19.  
  20. int *p = (int*)malloc(sizeof(int));
  21. *p = k;
  22.  
  23. //Used to terminate a thread and the return value is passed as a pointer
  24. pthread_exit(p);
  25. }
  26.  
  27. //Driver code
  28. int main()
  29. {
  30.  
  31. int matA[MAX][MAX];
  32. int matB[MAX][MAX];
  33.  
  34.  
  35. int r1=MAX,c1=MAX,r2=MAX,c2=MAX,i,j,k;
  36.  
  37.  
  38. // Generating random values in matA
  39. for (i = 0; i < r1; i++)
  40. for (j = 0; j < c1; j++)
  41. matA[i][j] = rand() % 10;
  42.  
  43. // Generating random values in matB
  44. for (i = 0; i < r1; i++)
  45. for (j = 0; j < c1; j++)
  46. matB[i][j] = rand() % 10;
  47.  
  48. // Displaying matA
  49. for (i = 0; i < r1; i++){
  50. for(j = 0; j < c1; j++)
  51. printf("%d ",matA[i][j]);
  52. printf("\n");
  53. }
  54.  
  55. // Displaying matB
  56. for (i = 0; i < r2; i++){
  57. for(j = 0; j < c2; j++)
  58. printf("%d ",matB[i][j]);
  59. printf("\n");
  60. }
  61.  
  62.  
  63. int max = r1*c2;
  64.  
  65.  
  66. //declaring array of threads of size r1*c2
  67. pthread_t *threads;
  68. threads = (pthread_t*)malloc(max*sizeof(pthread_t));
  69.  
  70. int count = 0;
  71. int* data = NULL;
  72. for (i = 0; i < r1; i++){
  73. for (j = 0; j < c2; j++)
  74. {
  75.  
  76. //storing row and column elements in data
  77. data = (int *)malloc((20)*sizeof(int));
  78. data[0] = c1;
  79.  
  80. for (k = 0; k < c1; k++)
  81. data[k+1] = matA[i][k];
  82.  
  83. for (k = 0; k < r2; k++)
  84. data[k+c1+1] = matB[k][j];
  85.  
  86. //creating threads
  87. pthread_create(&threads[count++], NULL,
  88. mult, (void*)(data));
  89.  
  90. }
  91. }
  92. for(i=0 ; i<4 ;i++) printf("\ndata is %d " , data[i]);
  93. printf("RESULTANT MATRIX IS :- \n");
  94. for (i = 0; i < max; i++)
  95. {
  96. void *k;
  97.  
  98. //Joining all threads and collecting return value
  99. pthread_join(threads[i], &k);
  100.  
  101.  
  102. int *p = (int *)k;
  103. printf("%d ",*p);
  104. if ((i + 1) % c2 == 0)
  105. printf("\n");
  106. }
  107.  
  108.  
  109.  
  110. return 0;
  111. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement