2014-12-11 51 views
1

我得到一个分段错误(核心转储)错误,当我试图乘以两个矩阵线程 我做了这个程序在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 

变量是什么问题?

+0

[JS1](http://stackoverflow.com/users/4192931/js1)的[回复](http://stackoverflow.com/a/27415229/15168)提出了一些有效的观点。我在我的Mac上进行了一些测试,其中'TAM'设置为'300','NUM_THREADS'设为'25',文件为18,000个随机单位数字(1..9),变量'x' ,'y'和'z'做成局部变量,它对我来说似乎很好。 – 2014-12-11 04:49:44

回答

2

您不应该有x, y, z作为全局变量。如果你这样做,他们将在你的线程中共享,并且可能发生奇怪的事情。您应该在每个函数中将这些变量声明为局部变量。你也应该考虑用当地人或者TAM替换m, o, p,虽然这些都不会被分配到,所以它不那么重要。

+0

感谢男人,那就是解决方案,全局变量 – MrRoboto 2014-12-11 05:18:11