c - matrix multiplication using thread where each thread compute a row -
hello guys , wrote below code matrix multiplication using thread, each thread should compute row when run code gives me correct result first row , other rows of elements zeros. martix size of m*m !! can't find mistake !!thanks in advance
# include <stdio.h> # include <pthread.h> # include <stdlib.h> #include <sys/time.h> int m; int [100][100]; int b [100][100]; int c [100][100]; struct v { int i; /* row */ int j; /* column */ }; void *runner(void *param); /* thread */
int main() { clock_t cstart = clock(); clock_t cend = 0; int count=0; pthread_t tid; int icount,jcount,kcount; printf("enter size: \n"); scanf("%d",&m); for(icount=0;icount<m;icount++) { for(jcount=0;jcount<m;jcount++) { printf("enter mat1[%d][%d] :",icount,jcount); scanf("%d",&a[icount][jcount]); } } for(icount=0;icount<m;icount++) { for(jcount=0;jcount<m;jcount++) { printf("enter mat2[%d][%d] :",icount,jcount); scanf("%d",&b[icount][jcount]); } } for(icount = 0; icount < m; icount++) { struct v *data = (struct v *) malloc(sizeof(struct v)); data->i = icount; data->j = jcount; pthread_t tid; pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&tid,&attr,runner,&c[icount]); pthread_join(tid, null); count++; } printf("\n matrix 1 \n"); for(icount=0;icount<m;icount++) { for(jcount=0;jcount<m;jcount++) { printf("%d \t",a[icount][jcount]); } printf("\n"); } printf("\n matrix 2 \n"); for(icount=0;icount<m;icount++) { for(jcount=0;jcount<m;jcount++) { printf("%d \t",b[icount][jcount]); } printf("\n"); } printf("\n multipication of matrices ...\n"); for(icount = 0; icount < m; icount++) { for(jcount = 0; jcount < m; jcount++) { printf("%d \t", c[icount][jcount]); } printf("\n"); } cend = clock(); printf ("it took %.3f cpu sec\n", ((double)cend - (double)cstart)* 1.0e-6); return 0; }
void *runner(void *param) { struct v *data = param; int n, sum = 0; int jcount; do{sum=0; for(n = 0; n< m; n++){ sum += a[data->i][n] * b[n][data->j]; } c[data->i][data->j] = sum; data->j++; }while(data->j<m); pthread_exit(0); }
// compile code : gcc thread.c -o out -pthread // ./out
the mistake here in thread creation loop:
data->j = jcount; you should initialize data->j 0. instead initialize jcount value m @ end of matrix initialization phase. data->j not make sense thread argument each thread computes whole column.
Comments
Post a Comment