我想使用线程进行矩阵乘法,每个线程执行一次乘法,然后主线程将所有结果相加,并将它们放在最终矩阵的适当位置(在其他线程退出后)。我尝试的方法是创建一个单行数组,其中包含每个线程的结果。然后我会遍历数组并将结果相加并放置在最终矩阵中。例如:如果您有以下矩阵:A = [{1,4}, {2,5}, {3,6}]和B = [{8,7,6}, {5,4,3}],那么我想要一个包含[8,20,7,16,6,12,16等]的数组。然后,我会循环遍历数组,将每两个数字相加并将它们放置在我的最终数组中。这是我的作业任务,因此我不需要完整的代码,但需要一些逻辑来正确存储数组中的结果。我在如何跟踪每个矩阵中的位置以避免遗漏任何数字方面遇到了困难。谢谢。编辑2:必须为每个乘法操作分配单个线程。也就是说,对于上面的示例,将有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/
这篇文章介绍了如何在Linux上使用Pthreads进行矩阵乘法计算。通过将矩阵划分为块,每个线程可以处理一个块的计算,从而提高计算效率。作者提供了完整的代码和详细的注释,方便读者学习和理解。
C
,确定需要多少行乘以列的向量乘法,将后者除以前者(大约),并将其发送给C
个线程独立处理。任何模数(多出来的向量直到C-1
)都会作为额外的乘法发送给第一系列线程。你很难找到一个更高效和简单的算法,尤其是考虑到根本不需要任何锁定。 - WhozCraigA[500][800] x B[800][1000]
这样的东西时,概念很快就会降级。它变得越大,你花费的时间就越多,而这些时间本可以用来进行更多的乘法运算。唉,祝你好运! - WhozCraig