C 多线程矩阵乘法中的分段错误 #包括 #包括 国际注册汇率[1000][1000]; 国际巴西里亚尔[1000][1000]; int-h; int f; void*BMM(void*arg) { int*neo=(int*)arg; int-ne=*近地天体; 整数和=0; 对于(int i=0;i
上面的程序应该使用3个线程将矩阵的第一行乘以其他矩阵的所有列,然后将第二行乘以所有其他列,以此类推,然后将各自的值存储到另一个矩阵中,但它给出了分段错误。我哪里出错了?我想你的问题在这里:C 多线程矩阵乘法中的分段错误 #包括 #包括 国际注册汇率[1000][1000]; 国际巴西里亚尔[1000][1000]; int-h; int f; void*BMM(void*arg) { int*neo=(int*)arg; int-ne=*近地天体; 整数和=0; 对于(int i=0;i,c,multithreading,matrix,pthreads,C,Multithreading,Matrix,Pthreads,上面的程序应该使用3个线程将矩阵的第一行乘以其他矩阵的所有列,然后将第二行乘以所有其他列,以此类推,然后将各自的值存储到另一个矩阵中,但它给出了分段错误。我哪里出错了?我想你的问题在这里: #include <stdio.h> #include <pthread.h> int arr[1000][1000]; int brr[1000][1000]; int h; int f; void *BMM(void *arg) { int* neo = (int*) ar
#include <stdio.h>
#include <pthread.h>
int arr[1000][1000];
int brr[1000][1000];
int h;
int f;
void *BMM(void *arg)
{
int* neo = (int*) arg;
int ne = *neo;
int sum = 0;
for(int i = 0; i < n; ++i)
{
sum += arr[x][i]*brr[x][f];
++f;
}
printf("%d\n", sum);
crr[x][h] = sum;
pthread_exit(NULL);
}
int main()
{
pthread_t* ar = malloc(3*sizeof(*ar));
printf("Enter the value of m and n\n");
scanf("%d %d",&m,&n);
for(int i = 0; i < m; ++i)
{
for(int j = 0; j < n; ++j)
{
scanf("%d",&arr[i][j]);
}
}
printf("Enter the value of p and q\n");
scanf("%d %d",&p,&q);
if(p != n)
{
printf("The matrix multiplication is not possible\n");
return 0;
}
int* id;
id = (int *)malloc(4*sizeof(int));
for(int i = 0; i < p; ++i)
{
for(int j = 0; j < q; ++j)
{
scanf("%d",&brr[i][j]);
}
}
for(x = 0; x < m; ++x)
{
for(z = 0; z < q; z+=4)
{
f = z;
h = z;
for(int k = 0; k < 3; ++k)
{
pthread_create(&ar[k],NULL,BMM,NULL);
}
for(int k = 0; k < 3; ++k)
{
pthread_join(ar[k],NULL);
}
}
}
for (int i = 0; i < m; ++i)
{
for(int j = 0; j < q; ++j)
{
printf("%d ",crr[i][j]);
}
printf("\n");
}
}
然后:
pthread_create(&ar[k],NULL,BMM,NULL);
^^^^
void *arg is NULL
此外,这看起来很奇怪:
void *BMM(void *arg)
{
int* neo = (int*) arg;
int ne = *neo; // Dereference NULL --> segmentation fault
及
甚至没有试着调试它?甚至不知道SEGFULT发生在哪里?什么是
x
,它是在哪里定义的,设置在哪里?糟糕的是,我忘了贴花x,但就调试而言,我非常确定错误在我创建线程或加入线程的部分,因为当我调试程序时,函数没有执行。但是我不知道哪里出了问题。当要求对意外的运行时行为进行故障排除时,您应该发布实际编译的代码……注意,没有检查用户的输入,并且您的矩阵是静态分配的。这是造成灾难的原因,因为您可以很容易地写出矩阵边界。我猜测(因为未显示)OP正在使用全局定义的变量n
和x
,它们是调用函数中的循环控制变量。@WeatherVane-全局变量。。。嗯,我想你是对的。然而,对于多线程实现来说,这是非常奇怪的。无论如何,这并没有改变OP取消引用NULL的事实。
void *BMM(void *arg)
{
int* neo = (int*) arg;
int ne = *neo; // ne is never used !!
int sum = 0;
for(int i = 0; i < n; ++i) // Where does n come from ?
if (scanf("%d %d",&m,&n) != 2)
{
// Add error handling here
}
if (scanf("%d",&arr[i][j]) != 1)
{
// Add error handling here
}