使用pthreads的矩阵乘法 [英] Matrix multiplication using pthreads

查看:924
本文介绍了使用pthreads的矩阵乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用的pthreads和创造的每一行,而不是每个元素的计算每一个线程做矩阵乘法。假设有两个矩阵
A [M] [K],B [K] [N]。我在哪里去了?

  int类型的[M] [K];
INT B〔K] [N];
INT C [] [];void *的亚军(无效*参数);
结构v
{
INT I;
 诠释J;
};工业贸易署的pthread_t [M]。对于(i = 0; I<米;我++)//它应该创建中号线
{
    结构V *数据=(结构V *)malloc的(的sizeof(结构V));
    数据 - > I = I;
    数据 - >当J = J;
    在pthread_create(安培; TID [计数],&安培; attr指示,亚军,数据);
    在pthread_join(TID [计数],NULL);
    算上++;
}亚军(无效*参数)//
{
    结构V *测试;
    INT T = 0;
    测试=(结构V *)参数;    对于(t = 0; T&所述; k;吨++)//欲计算它为一排,而不是一个元素的
    {
        C [测试 - > I] [测试 - > J] = C [测试 - > I] [测试 - > J] + A [测试 - > I] [T] * B [T] [测试 - > J]。
    }
    了pthread_exit(0);
}


解决方案

首先,摆脱数据 - > j的。如果你计算整个行的行索引你的线程需要的唯一的事。现在你的亚军(..)计算一个元素。你必须通过一个遍历所有行元素计算其中之一。
其次,不要加入被创建之后的线程。这样,你只有一个线程同时运行。启动连接螺纹已创建的所有线程时。

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);
}

解决方案

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.

这篇关于使用pthreads的矩阵乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆