【问题标题】:Segmentation fault on calling pthread_create, passing a struct调用 pthread_create 时出现分段错误,传递结构
【发布时间】:2017-04-23 15:32:24
【问题描述】:

我正在做一些需要使用 pthread 的事情。基本上,我想在矩阵上找到最大值,但我没有做所有的单处理工作,而是使用pthreads 来打破它。 我使用如下定义的一个结构向findMaxPerArea 函数输入多个值。当我在最后一行调用pthread_create(...); 时,问题就出现了。 printf 在它通过之前就好了。 请不要对我太苛刻,因为我知道这一定是一个愚蠢的错误。有什么想法吗?

struct inputData{
  int ** array;
  int start, stop, cols, threadID;
  int* localmax;
};


void* findMaxPerArea(void* tmp){
  struct inputData* inp = (struct inputData*) tmp;
  inp->localmax[inp->threadID] = 0;
  int i, j;
  for(i = inp->start; i < inp->stop; i++){
    for(j = 0; j < inp->cols; j++){
      if(inp->array[i][j] > inp->localmax[inp->threadID]) inp->localmax[inp->threadID] = inp->array[i][j];
    }
  }
}


int main(){
  int N, p;

  printf("Give me the number of threads\n");
  scanf("%d", &p);
  printf("Give me the number of rows and columns (one value)\n");
  scanf("%d", &N);

  int* localmax = malloc(p * sizeof(int));
  pthread_t* threadArr = (pthread_t*) malloc(p*sizeof(pthread_t));

  int** a = malloc(N * sizeof(int*));
  for (int i = 0; i < N; i++) {
    a[i] = malloc(N * sizeof(int));
  }
  for(int i = 0; i < N; i++){
    for(int j = 0; j < N; j++){
      a[i][j] = 5;
    }
  }
  a[0][1] = 8;
  a[1][1] = 13;
        struct inputData* inputArray = (struct inputData*) malloc(p * sizeof(struct inputData));
          for(int i = 0; i < p; i++){
            inputArray[i].array = a;
            inputArray[i].start = i*(N/p);
            inputArray[i].stop = (N/p)*(i+1) - 1;
            inputArray[i].cols = N;
            inputArray[i].threadID = i;
            inputArray[i].localmax = localmax;
            printf("It passes this\n");
            pthread_create((pthread_t*)threadArr[i], NULL, findMaxPerArea, (void*)&inputArray[i]);
          }}

【问题讨论】:

  • 使用您向我们展示的当前代码 sn-p,很难对您的代码进行推理。请将您的问题扩展到minimal, complete and verifiable example
  • 我更新了我的答案,这是我的全部代码。
  • 不要使用演员表。就是这么简单。 (不,实际上没那么简单。有时你必须这样做。但作为第一个近似值,这条规则是有效的。你可以花费数年时间做 C 而不编写一个演员表。当你最终需要一个时,希望你有足够的经验去做对。)

标签: c pthreads


【解决方案1】:
pthread_create((pthread_t*)threadArr[i], NULL, findMaxPerArea, (void*)&inputArray[i]);

threadArr[i] 转换为pthread_t* 没有意义,因为您将值转换为指针。相反,您想完全省略演员表(因为您已经在处理 pthread_ts 的数组)并获取 ith 元素的地址:

&threadArr[i] 

【讨论】:

  • @GusAndrianos 不客气,但请不要在 StackOverflow 上使用任何脏话,它一点也不受欢迎,并且可能会删除您的问题和答案。
  • 抱歉,我搜索了将近一个小时。
猜你喜欢
  • 2021-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-02
  • 2021-11-08
  • 2014-05-31
  • 2011-03-23
相关资源
最近更新 更多