c - 使用pthread执行矩阵乘法

标签 c linux gcc pthreads unix

我的两个矩阵都只包含一个,每个数组都有 500 行和列。因此,生成的矩阵应该是所有元素都具有 500 值的矩阵。但是,我得到了 res_mat[0][0]=5000。甚至其他元素也是5000。为什么

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>

#define ROWS 500
#define COLUMNS 500
#define N_THREADS 10

int mat1[ROWS][COLUMNS],mat2[ROWS][COLUMNS],res_mat[ROWS][COLUMNS];

void *mult_thread(void *t)
{   
    /*This function calculates 50 ROWS of the matrix*/

    int starting_row;
    starting_row = *((int *)t);
    starting_row = 50 * starting_row;

    int i,j,k;
    for (i = starting_row;i<starting_row+50;i++)
        for (j=0;j<COLUMNS;j++)
            for (k=0;k<ROWS;k++)
                res_mat[i][j] += (mat1[i][k] * mat2[k][j]);
    return;
}

void fill_matrix(int mat[ROWS][COLUMNS])
{
    int i,j;
    for(i=0;i<ROWS;i++)
        for(j=0;j<COLUMNS;j++)
            mat[i][j] = 1;
}

int main()
{
    int n_threads = 10; //10 threads created bcos we have 500 rows and one thread calculates 50 rows
    int j=0;
    pthread_t p[n_threads];

    fill_matrix(mat1);
    fill_matrix(mat2);
    for (j=0;j<10;j++)
        pthread_create(&p[j],NULL,mult_thread,&j);

    for (j=0;j<10;j++)
        pthread_join(p[j],NULL);

    printf("%d\n",res_mat[0][0]);
    return 0;
}

最佳答案

我不知道这是否是您问题的原因,但是:

    pthread_create(&p[j],NULL,mult_thread,&j);

肯定坏了。您正在传递 j &j 的地址。所以每个线程在真正启动的时候都会得到一个随机值0 <= starting_row <= 9。最好只传入 (void*)j 并使用 (int)j 将其取出。

您也永远不会初始化 res_mat,但 IIRC 无论如何它都会被初始化。

编辑: starting_row 的值是随机的,因为 j 在线程启动和加入之间遍历了 0 到 9 之间的所有数字。 因此线程将在这两者之间的某个随机点启动,并在该点获取 j 的值。

关于c - 使用pthread执行矩阵乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2446122/

相关文章:

linux - 如何在Linux中使用sed将文本文件分割成10个以上字符的 block 而不分割单词?

linux - 将 grep 的输出写入 Linux 上的文件?

linux - 使用 bash 脚本使用列表将单个文件发送到多台计算机

c - 与 while 语句相关的 GCC 编译错误

c - GCC预处理: Leave undefined Conditionals without assuming zero-values

c - atoi、atol 和 stoi 分别代表什么?

c - ALSA Lib 1.1.2 编译错误

c - 在 C 中用分隔符拆分字符串

c - C 中值之间的意外类型转换

c++ - 捕获未分配的 r 值的编译器选项