fork download
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <time.h>
  5. #define size 10
  6. #define M size
  7. #define K size
  8. #define N size
  9.  
  10. // int A [M][K] = { {1,4}, {2,5}, {3,6} };
  11. // int B [K][N] = { {8,7,6}, {5,4,3} };
  12.  
  13. int A [M][K];
  14. int B [K][N] ;
  15. int C [M][N];
  16.  
  17. struct v {
  18. int i; /* row */
  19. int j; /* column */
  20. };
  21.  
  22. void *runner(void *param); /* the thread */
  23.  
  24. void fill_matrix(int matrix[][N], int row, int column)
  25. {
  26. // int (*matrix)[row] = malloc(sizeof(int[row][column]));
  27. for (int i = 0; i < row; i++)
  28. {
  29. for (int j = 0; j < column; j++)
  30. {
  31. matrix[i][j] = (rand() % (100-0+1)) + 1;
  32. }
  33. }
  34. return;
  35. }
  36.  
  37. int main(int argc, char *argv[]) {
  38.  
  39. int i,j, count = 0;
  40. // int (*A)[M] = malloc(sizeof(int[M][K]));
  41. // int (*B)[K] = malloc(sizeof(int[K][N]));
  42. // A = (int*)malloc(sizeof(A));
  43.  
  44. fill_matrix(A,M,K);
  45. fill_matrix(B,K,N);
  46. clock_t start = clock();
  47. // pthread_t thread_array[M*N];
  48. pthread_t thread_array[M*N]; //malloc(M*N * sizeof(pthread_t));
  49.  
  50. pthread_attr_t attr;
  51. pthread_attr_init(&attr);
  52. for(i = 0; i < M; i++) {
  53. for(j = 0; j < N; j++) {
  54. //Assign a row and column for each thread
  55. struct v *data = (struct v *) malloc(sizeof(struct v));
  56. data->i = i;
  57. data->j = j;
  58. /* Now create the thread passing it data as a parameter */
  59. //pthread_t tid; //Thread ID
  60. //pthread_attr_t attr; //Set of thread attributes
  61. //Get the default attributes
  62. //pthread_attr_init(&attr);
  63. //Create the thread
  64.  
  65. pthread_create(&thread_array[count],&attr,runner,data);
  66. //Make sure the parent waits for all thread to complete
  67. //pthread_join(tid, NULL);
  68. count++;
  69. }
  70. }
  71. for(int k =0;k<M*N;k++){
  72. pthread_join(thread_array[k],NULL);
  73. }
  74. clock_t end = clock();
  75. printf("%f\n",(float)(end-start)/CLOCKS_PER_SEC );
  76.  
  77. //Print out the resulting matrix
  78. //for(i = 0; i < M; i++) {
  79. // for(j = 0; j < N; j++) {
  80. // printf("%d ", C[i][j]);
  81. // }
  82. // printf("\n");
  83. // }
  84. }
  85.  
  86. //The thread will begin control in this function
  87. void *runner(void *param) {
  88. struct v *data = param; // the structure that holds our data
  89. int n, sum = 0; //the counter and sum
  90.  
  91. //Row multiplied by column
  92. for(n = 0; n< K; n++){
  93. sum += A[data->i][n] * B[n][data->j];
  94. }
  95. //assign the sum to its coordinate
  96. C[data->i][data->j] = sum;
  97.  
  98. //Exit the thread
  99. pthread_exit(0);
  100. }
Success #stdin #stdout 0s 4440KB
stdin
Standard input is empty
stdout
0.000482