当我尝试将两个矩阵与线程相乘时出现段错误(核心已转储)错误 我用 C 编写了这个程序并且在 TAM<=200 下工作正常但是当我插入一个高值时线程不起作用。 这是代码:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "tamanio.h"
#define NUM_THREADS 4
int matrizA[TAM][TAM];
int matrizB[TAM][TAM];
int matrizR[TAM][TAM];
int x,y,z;
int m=TAM,o=TAM,p=TAM;
clock_t start_t, end_t;
double total_t;
//THREADS
void *mul(void *threadid){
long tid;
tid = (long) threadid;
int OTHERCONTROL=tid*TAM/NUM_THREADS;
int VARCONTROLTHREAD=(tid+1)*TAM/NUM_THREADS;
printf("Iniciando hilo %ld ...\n", tid);
//multiply
for(x=OTHERCONTROL; x<VARCONTROLTHREAD; x++){
for(y=0; y<o; y++){
for(z=0;z<p;z++){
matrizR[x][y]+=matrizA[x][z]*matrizB[z][y];
}
}
}
printf("Hilo %ld terminado.\n", tid);
pthread_exit((void*) threadid);}
int main (int argc, char **argv){
//variables
FILE *entrada;
char *nombre;
//Read
if (argc > 1){
nombre =argv[1];
entrada =fopen(nombre, "r");
if(entrada == NULL){
printf("Hubo problemas al intentar abrir el archivo de entrada\n");
exit(1);
}
}
// MatrizA
for(x=0; x<m; x++){
for(y=0; y<o; y++){
fscanf(entrada,"%d\t",&(matrizA[x][y]));
}
}
// MatrizB
for(x=0; x<m; x++){
for(y=0; y<o; y++){
fscanf(entrada,"%d\t",&(matrizB[x][y]));
}
}
fclose(entrada);
printf("Se termina la lectura de datos\n");
start_t=clock();
//**THREADS**
pthread_t threads[NUM_THREADS];
int rc;
long t;
void *status;
for(t=0;t<NUM_THREADS;t++){
printf("creando hilo%ld\n",t);
rc=pthread_create(&threads[t],NULL,mul,(void *)t);
if(rc){
printf("ERROR\n");
exit(-1);
}
}
for(t=0; t<NUM_THREADS; t++) {
rc = pthread_join(threads[t], &status);
if (rc) {
printf("ERROR; El codigo de retorno de pthread_join() es %d\n", rc);
exit(-1);
}
printf("Main: se completo la union con el hilo %ld regresando un estado de %ld\n",t,(long)status);
}
end_t=clock();
total_t = (double) (end_t - start_t) / CLOCKS_PER_SEC;
printf("Tiempo de ejecucion: %f \n",total_t);
printf("END MAIN\n");
pthread_exit(NULL);
return 0;
}
tamanio.h 只包含一个名为 TAM 的变量
#define TAM 1000
有什么问题吗?
最佳答案
你不应该将 x, y, z
作为全局变量。如果这样做,它们将在您的线程之间共享,并且可能会发生奇怪的事情。您应该在每个函数中将这些变量声明为局部变量。您还应该考虑将 m, o, p
替换为 locals 或只是 TAM
,尽管这些从未分配给,因此它不太重要。
关于c - 线程的段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27414413/