【问题标题】:Segmentation fault (core dumped) with Threads带有线程的分段错误(核心转储)
【发布时间】:2014-12-11 02:30:45
【问题描述】:

当我尝试将两个矩阵与线程相乘时出现分段错误(核心转储)错误 我用 C 语言编写了这个程序,并且在 TAM

#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

有什么问题吗?

【问题讨论】:

  • JS1's answer 提出了一些有效的观点。我在我的 Mac 上做了一些测试,TAM 设置为 300NUM_THREADS 设置为25,文件包含 18,000 个随机个位数 (1..9),变量为 x , yz 变成局部变量,对我来说似乎工作正常。

标签: c multithreading


【解决方案1】:

您不应该将x, y, z 作为全局变量。如果您这样做,它们将在您的线程之间共享,并且可能会发生奇怪的事情。您应该在每个函数中将这些变量声明为局部变量。您还应该考虑将 m, o, p 替换为本地人或只是 TAM,尽管这些从未分配给,所以它不太重要。

【讨论】:

  • 谢谢各位,这就是解决方案,全局变量
猜你喜欢
  • 2019-09-09
  • 2012-11-19
  • 2017-08-18
  • 1970-01-01
  • 2016-03-19
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
相关资源
最近更新 更多