Matrix multiplication using pthreads

你。 提交于 2019-12-13 05:46:31

问题


I am trying to do matrix multiplication using pthreads and creating one thread for each computation of each row instead of each element. Suppose there are two matrices A[M][K],B[K][N] . Where am I going wrong ?

int A[M][K];
int B[K][N];
int C[][];

void *runner (void *param);


struct v
{
int i;
 int j;
};

pthread_t tid[M];

for (i = 0; i < M; i++) // It should create M threads 
{
    struct v *data = (struct v *) malloc (sizeof (struct v));
    data->i = i;
    data->j = j;
    pthread_create (&tid[count], &attr, runner, data);
    pthread_join (tid[count], NULL);
    count++;
}

runner (void *param) //
{
    struct v *test;
    int t = 0;
    test = (struct v *) param;

    for (t = 0; t < K; t++)  // I want to compute it for a row instead of an element 
    {
        C[test->i][test->j] = C[test->i][test->j] + A[test->i][t] * B[t][test->j];
    }
    pthread_exit (0);
}

回答1:


First, get rid of data->j. If you are computing entire rows the row index is the only thing your thread needs. Right now your runner(..) computes a single element. You have to iterate over all row elements computing them one by one. Second, do not join a thread right after it is created. This way you have only one thread running at a time. Start joining threads when all threads have been created.



来源:https://stackoverflow.com/questions/14881046/matrix-multiplication-using-pthreads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!