这是一个矩阵乘法代码。它创建一个线程将第一个矩阵的每一行与第二个矩阵相乘,并将结果保存在矩阵 C 中。
它在 pthread_create 行expected Primary-expression before 'void'
中给出错误。
我在 ubunto 13.10 虚拟机上运行此代码。
提前致谢。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
struct matrices
{
int matrixA[10][10];
int matrixB[10][10];
int matricC[10][10];
int r1,r2,c1,c2;
}*ptr;
int p;
void *matrixMul(void *);
int main()
{
int i=0,j=0;
pthread_t threads[10];
ptr=(struct matrices*)malloc(sizeof(struct matrices));
printf("Enter size of first matrix(Rows then Columns)");
scanf("%d",&(ptr->r1));
scanf("%d",&(ptr->c1));
printf("Enter elements of first array : ");
for(i=0; i<ptr->r1; i++)
{
for(j=0; j<ptr->c1; j++)
{
scanf("%d",&ptr->matrixA[i][j]);
}
}
printf("Enter size of second matrix(Rows then Columns)");
scanf("%d",&(ptr->r2));
scanf("%d",&(ptr->c2));
if(ptr->c1!=ptr->r2)
{
printf("Dimensions ERRORR! ");
}
else
{
printf("Enter elements of second array : ");
for(i=0; i<ptr->r2; i++)
{
for(j=0; j<ptr->c2; j++)
{
scanf("%d",&ptr->matrixB[i][j]);
}
}
for(i=0;i<ptr->r1;i++)
{
for(j=0;j<ptr->c2;j++)
{
ptr->matricC[i][j]=0;
}
}
for (p=0;p<ptr->r1;p++)
{
**********pthread_create(&threads[p],NULL, *matrixMul,void &p);**********
}
for(i=0;i<ptr->r1;i++)
{
pthread_join(threads[i],NULL);
}
for(i=0;i<ptr->r1;i++)
{
for(j=0;j<ptr->c2;j++)
{
printf("%d",ptr->matricC[i][j]);
}
}
}
return 0;
}
void *matrixMul(void *rownum)
{
int *i;
int n=0,m=0;
i=(int*)rownum;
for(n=0;n<ptr->c2;n++)
{
for(m=0;m<ptr->c1;m++)
{
ptr->matricC[*i][n]+=(ptr->matrixA[*i][m])*(ptr->matrixB[m][n]);
}
}
return NULL;
}
最佳答案
您的代码包含一些小错误,但逻辑是正确的,不用担心。
我下载了代码并在我的机器上进行了测试,因此请注意以下事项:
这一行应该这样写...
pthread_create(&threads[i],NULL, matrixMul, &i);
因为根据pthread library的规范pthread_create 应该采用指向运行器函数的 void 指针和指向参数的 void 指针。您不需要添加 (void *)
,因为您已经将运行程序函数 matrixMul
声明为 void *
。
您的主要错误是(void) &i
,它应该是&i
,因为您已经将此参数设置为void *
在运行器函数的原型(prototype)中。您也应该像这样 &matrixMul
一样传递 runner 函数。
其他一些注释:“代码审查”
- 您不应该将逻辑放在 else 语句中,您可以简单地在
printf("Dimensions ERRORR! ");
之后编写exit(-1);
因为如果尺寸错误,这基本上就是您要做的事情。 - 检查
pthread_create
和pthread_join
的返回值(状态)
关于调用 pthread_create 错误 - 预期主表达式在 'void' 之前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23689545/