gpt4 book ai didi

c - 使用多线程的矩阵乘法中的段错误

转载 作者:行者123 更新时间:2023-11-30 18:50:40 26 4
gpt4 key购买 nike

#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");
}
}

上面的程序应该通过使用 3 个线程将矩阵的第一行乘以其他矩阵的所有列来乘以两个矩阵,然后将第二行乘以所有其他列,依此类推,然后将各自的值存储到另一个矩阵中,但是它给出了段错误。我哪里出错了?

最佳答案

我认为你的问题在这里:

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

此外,这看起来很奇怪:

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 ?

也许应该是n而不是ne

如果nxfh是全局变量,那么你就会遇到麻烦,因为所有线程都会对相同的变量进行处理。那真是太糟糕了。每个线程都需要它自己的变量。

BTW:

始终检查 scanf 返回的值 - 类似于:

if (scanf("%d %d",&m,&n) != 2)
{
// Add error handling here
}

if (scanf("%d",&arr[i][j]) != 1)
{
// Add error handling here
}

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

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