使用pthreads进行矩阵乘法

时间:2013-02-14 17:53:57

标签: c multithreading matrix-multiplication

我正在尝试使用pthreads进行矩阵乘法,并为每行的每次计算而不是每个元素创建一个线程。假设有两个矩阵 A [M] [K],B [K] [N]。我哪里错了?

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 个答案:

答案 0 :(得分:1)

首先,摆脱数据 - &gt; j。如果要计算整行,则行索引是您的线程唯一需要的东西。现在你的跑步者(..)计算一个单独的元素。您必须迭代遍历所有行元素逐个计算它们。 其次,不要在创建后立即加入线程。这样,您一次只能运行一个线程。在创建所有线程后开始加入线程。