Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

c - Matrix multiplication using pthreads

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...