Reputation: 21
I get a Segmentation fault (core dumped) Error when i tried to multiply two matrix with threads I made this program in C and works fine with TAM<=200 but when i insert a high value the threads doesn't work. This is the code:
#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 just contain a variable called TAM
#define TAM 1000
Is something wrong?
Upvotes: 1
Views: 256
Reputation: 4767
You should not have x, y, z
as global variables. If you do, they will be shared amongst your threads and strange things can happen. You should declare those variables as local variables in each function. You should also think about replacing m, o, p
with either locals or just TAM
, although these are never assigned to, so it is less important.
Upvotes: 2