我正在寻找使用线程进行矩阵乘法,其中每个线程进行一次乘法,然后主线程将所有结果相加并将它们放在最终矩阵中的适当位置(在其他线程退出之后)。
我尝试这样做的方法是创建一个包含每个线程结果的单行数组。然后我会遍历数组并将结果添加到最终矩阵中。
例如:如果你有矩阵:
A = [{1,4}, {2,5}, {3,6}] B = [{8,7,6}, {5,4,3}]
然后我想要一个包含 [8, 20, 7, 16, 6, 12, 16 等] 的数组,然后我将遍历数组,将每 2 个数字相加并将它们放在我的最终数组中。
这是一个硬件分配,所以我不是在寻找确切的代码,而是关于如何将结果正确存储在数组中的一些逻辑。我正在为如何跟踪我在每个矩阵中的位置而苦苦挣扎,这样我就不会错过任何数字。
谢谢。
EDIT2:忘了提到每次乘法都必须有一个线程。对于上面的例子来说,将有 18 个线程,每个线程都进行自己的计算。
编辑:我目前正在使用此代码作为工作的基础。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define M 3
#define K 2
#define N 3
#define NUM_THREADS 10
int A [M][K] = { {1,4}, {2,5}, {3,6} };
int B [K][N] = { {8,7,6}, {5,4,3} };
int C [M][N];
struct v {
int i; /* row */
int j; /* column */
};
void *runner(void *param); /* the thread */
int main(int argc, char *argv[]) {
int i,j, count = 0;
for(i = 0; i < M; i++) {
for(j = 0; j < N; j++) {
//Assign a row and column for each thread
struct v *data = (struct v *) malloc(sizeof(struct v));
data->i = i;
data->j = j;
/* Now create the thread passing it data as a parameter */
pthread_t tid; //Thread ID
pthread_attr_t attr; //Set of thread attributes
//Get the default attributes
pthread_attr_init(&attr);
//Create the thread
pthread_create(&tid,&attr,runner,data);
//Make sure the parent waits for all thread to complete
pthread_join(tid, NULL);
count++;
}
}
//Print out the resulting matrix
for(i = 0; i < M; i++) {
for(j = 0; j < N; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}
}
//The thread will begin control in this function
void *runner(void *param) {
struct v *data = param; // the structure that holds our data
int n, sum = 0; //the counter and sum
//Row multiplied by column
for(n = 0; n< K; n++){
sum += A[data->i][n] * B[n][data->j];
}
//assign the sum to its coordinate
C[data->i][data->j] = sum;
//Exit the thread
pthread_exit(0);
}
资料来源: http: //macboypro.wordpress.com/2009/05/20/matrix-multiplication-in-c-using-pthreads-on-linux/