Pthreads的动态矩阵乘法

我是线程编程和C的初学者,我正试图弄清楚如何使用Pthreads进行简单的矩阵乘法。 我想为每个列创建一个线程,并将结果放在Result Matrix中。 我正在尝试动态地执行它,这意味着允许用户使用输入作为大小来创建两个nxn矩阵。

我的代码现在,不包括填充矩阵和读取大小n如下:

#include  #include  #include typedef struct Matrix { int line, col, size; double (*MA)[]; double (*MB)[]; double (*MC)[]; } Matrix; void *multiply(void *arg) { Matrix* work = (Matrix*) arg; int s, z; s = work->col; z = work->line; work->MC[0][0] = 0.0.//can't use MC, MB, MA here!! return 0; } int main() { Matrix* m; //read size and set it to int size (miissing here, does work) double MA[size][size], MB[size][size], MC[size][size]; int i, j; //filling the matrices (missing here, does work) pthread_t threads[size]; for (i = 0; i size = size; m->col = i; pthread_create(&threads[i], NULL, multiply, m); } for (i = 0; i < size; i++) { pthread_join(threads[i], NULL); } return 0; } 

问题是,我不能在乘法方法中使用MA,MB和NC(:=结果),而是在代码中显示它。 我只是得到错误“无效使用具有非特定边界的数组”,即使我在main方法中声明了所有这三个。

我理解这里有什么问题,或者我该如何解决? 我尝试调整我的讲座示例,其中将创建每个元素的线程。 提前致谢!

关于错误:

  work->MC[0][0] = 0.0.//can't use MC, MB, MA here!! 

MC被声明为double (*MC)[]并且您尝试将其用作二维数组,就像您声明它是double MC[N]{M] 。 当且仅当第一个维度被修复或者您逐行分配时,您可以使用两个(或更多)维数组。

所以你的程序可能是:

 #include  #include  #include typedef struct Matrix { int line, col, size; double MA[][]; double MB[][]; double MC[][]; } Matrix; void *multiply(void *arg) { Matrix* work = (Matrix*) arg; int s, z; s = work->col; z = work->line; work->MC[0][0] = 0.0 return 0; } int main() { Matrix* m; //read size and set it to int size (miissing here, does work) double MA[][], MB[][], MC[][]; int i, j; pthread_t threads[size]; MA = (double **) malloc(size * sizeof(double *)); MB = (double **) malloc(size * sizeof(double *)); MC = (double **) malloc(size * sizeof(double *)); for(int i=0;iMA = MA; m->MB = MB; m->MC = MC; m->size = size; m->col = i; pthread_create(&threads[i], NULL, multiply, m); } for (i = 0; i < size; i++) { pthread_join(threads[i], NULL); } return 0; } 

但是你必须注意线程可以同时访问数据,因此如果不同的线程可以使用和更改相同的值,你应该使用一些锁。