gpt4 book ai didi

c - 使用多线程的矩阵乘法?

转载 作者:太空狗 更新时间:2023-10-29 15:40:41 30 4
gpt4 key购买 nike

我应该使用线程将 2 个矩阵相乘。两件事:当我运行程序时,我总是得到 0。我还收到消息错误(对于每个错误,它在粗体行(我尝试打印输出的地方)上显示“警告:从不兼容的指针类型传递'printMatrix'的参数1”。还要注意,第一个 block 是粗体,那是我解决问题的尝试。我想我很接近,但我可能不是。有人能帮忙吗?谢谢 :)输出如下所示:一个=1 42 53 6乙=8 7 65 4 3A*B=0 0 00 0 00 0 0

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

#define M 3
#define K 2
#define N 3

struct v
{
int i; //row
int j; //column
};

int A[M][K] = {{1,4},{2,5},{3,6}};
int B[K][N] = {{8,7,6},{5,4,3}};
int C[M][N];

void *workerThread(void *data)
{
int i=((struct v*)data)->i;
int j=((struct v*)data)->j;
int accumulator = 0;

/*this is where you should calculate the assigned Cell. You will need to use the row(i) of
A and column[j] of B. Accumulate the result in accumulator */
**int k;
for(k=0; k<k; k++)
{
accumulator = A[i][k]*B[k][j];
}
C[i][j]=accumulator;
pthread_exit(NULL);**
}

void printMatrix(int *matrixIn, int rows, int columns)
{
int *matrix = matrixIn;
int i,j;
for (i=0;i<rows;i++)
{
}

int main (int argc, char *argv[])
{

pthread_t threads[M*N];
int i,j;
int counter = 0;
int numThreadsCreated = 0;

/*the following 5 lines demonstrates how to create 1 thread to calculate C[0][0], you
will need to create a loop for all of C's cells*/
struct v *data = (struct v *)malloc(sizeof(struct v));
data->i = 0; //assign the row of C for thread to calculate
data->j = 0; //assign the column of C for thread to calculate
pthread_create(&threads[0], NULL, workerThread, data);
numThreadsCreated++;

/*wait for all the threads to finish before printing out the matrices*/
for(j=0; j < numThreadsCreated; j++)
{
pthread_join( threads[j], NULL);
}

printf("A=\n");
**printMatrix(A,3,2);**
printf("B=\n");
**printMatrix(B,2,3);**
printf("A*B=\n");
**printMatrix(C,M,N);**
pthread_exit(NULL);
}

最佳答案

您的程序似乎为矩阵乘法实现了错误的编码算法。

下面这段代码看起来很荒谬:-

for(k=0; k<k; k++)
{
accumulator = A[i][k]*B[k][j];
}
C[i][j]=accumulator; // Not a code for matrix multiplication...

你应该实现类似的东西:-

for(i=0;i<M;i++){
for(j=0;j<N;j++){
accumulator=0;
for(int something=0;something<K;something++){
accumulator=accumulator+A[i][something]*B[something][j];
}
C[i][j]=accumulator;
accumulator=0;
}
}

关于c - 使用多线程的矩阵乘法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26478552/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com