多线程我想创建,其通过使用线程计算两个N * N的矩阵的乘法运算的C程序。
我参考启动此代码:Matrix Multiplication using multiple threads但不是对结果矩阵中的每个单元创建N * N个线程,我想创建N个线程做乘法同时在结果矩阵中的每一行都会被计算不同的线程。
我的代码看起来是这样的,到目前为止矩阵乘法在C
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#define N 2
struct v
{
int i;//Row
int j;//Column
};
int A[N][N]={{1,2},{3,4}};//Matrix 1
int B[N][N]={{2,3},{4,5}};//Matrix 2
int C[N][N];//Resulting Matrix
static void * fnc (void *arg)
{
struct v *data = (struct v *)arg;
int l;
for(l=0;l<N;l++)
{
int i=((struct v*)data[l]).i;//Row No
int j=((struct v*)data[l]).j;//Column No
int accumulator = 0;
int d,sum=0;
for (d = 0; d < N; d++)
{
sum = sum + A[i][d]*B[d][j];
}
C[i][j] = sum;
sum = 0;
}
return;
}
int main()
{
pthread_t threads[N];
int i,k;
for(i=0;i<N;i++)
{
struct v *data[N];
for(k=0;k<N;k++)
{
data[k]=(struct v *)malloc(sizeof(struct v));
data[k].i = i; //assign the row of C for thread to calculate
data[k].j = k; //assign the column of C for thread to calculate
}
//In this example it creates 2 threads with passing data.
//Data consists of row and column pairs for each thread, that will be calcuting the pairs.
//Consider first iteration of this loop:
//Thread 1 is created and data consists of (0,0) and (0,1) which are the targeted calculation cells for thread 1.
//In the second iteration: Thread 2 will have (1,0) and (1,1) pairs in its data.
pthread_create(&threads[i],NULL,fnc,data);
}
for(i=0; i < N; i++)
pthread_join(threads[i], NULL);
for (i = 0; i < N; i++)
for (k = 0; k < N; k++)
printf("%d\t", C[i][k]);
return 0;
}
当我编译
gcc thread.c -lpthread -lrt
我收到此错误:
thread.c: In function ‘fnc’:
thread.c:24:24: error: cannot convert to a pointer type
int i=((struct v*)data[l]).i;//Row No
^
thread.c:24:35: error: request for member ‘i’ in something not a structure or union
int i=((struct v*)data[l]).i;//Row No
^
thread.c:25:24: error: cannot convert to a pointer type
int j=((struct v*)data[l]).j;//Column No
^
thread.c:25:35: error: request for member ‘j’ in something not a structure or union
int j=((struct v*)data[l]).j;//Column No
^
thread.c: In function ‘main’:
thread.c:48:20: error: request for member ‘i’ in something not a structure or union
data[k].i = i; //assign the row of C for thread to calculate
^
thread.c:49:20: error: request for member ‘j’ in something not a structure or union
data[k].j = k; //assign the column of C for thread to calculate
我相信代码背后的逻辑是正确的,这肯定看起来像一个简单的参数传递问题。我把整个代码放在了一起,因为如果我收到你对这个问题的评论,并且为你期望的工作提供了一个更好的解决方案,我会很高兴。 谢谢。
有太多的问题,你应该阅读更多关于转换和你为什么尝试访问** - > **而不是**。**的变量?什么是**我**和** **是什么? – Michi
你是对的,来自C++的老习惯,我删除了 - >。 我也试图解释i和j在评论 –
既然你修正了一些编译器错误,你应该修改你的问题,以消除那些错误。 – Adam