【问题标题】:pthread segmentation fault (core dumped) errorpthread 分段错误(核心转储)错误
【发布时间】:2018-05-23 12:24:59
【问题描述】:

有人能指出为什么我的代码会引发分段错误吗?很可能我在拨打pthread_create() 时犯了一个错误,但我无法理解这个错误。有人能指出我哪里出错了吗?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

int x = 0;
int counter =
    0;  // This is the global variable that all the threads will increment.
pthread_mutex_t lock;

void* addcounter(void* threadid) {
  pthread_mutex_lock(&lock);
  int* id = (int*)threadid + 1;
  int* y = (int*)x;
  int total = (*id) * (*y);
  int i = 0;
  for (i = 0; i < total; i++) {
    counter += 1;
  }
  pthread_mutex_unlock(&lock);
}

int main(int argc, char* argv[]) {
  int thread_count = 0;
  int loop_count = 0;
  int expected_value = -1;

  if (argc != 3) {
    printf("Usage: threads <no_of_threads> <no_of_loops>\n");
    exit(1);
  }

  thread_count = atoi(argv[1]);
  loop_count = atoi(argv[2]);
  x = loop_count;

  // Start your implementation after this comment.
  pthread_t* threads;
  threads = malloc(sizeof(pthread_t) * thread_count);
  int t;
  int flag = 0;
  for (t = 0; t < thread_count; t++) {
    int* z = malloc(sizeof(int));
    *z = t;
    flag = pthread_create(&threads[t], NULL, addcounter, (void*)z);
  }
  if (flag != 0) {
    printf("error in creating threads");
    exit(0);
  }

  for (t = 0; t < thread_count; t++) pthread_join(threads[t], NULL);
  // Do not change the code below this comment
  return 0;
}

这段代码的输出是:

Segmentation fault (core dumped)

我应该如何解决这个错误?

【问题讨论】:

  • 是的,这是什么int* y = (int*) x;x 是整数而不是指针。
  • 用-g编译,用gdb运行,​​它会告诉你哪里崩溃了
  • Ohh Bo Persson 明白了
  • @BoPersson 我应该改变什么?
  • "(int*)threadid + 1;" 为什么是+1

标签: c segmentation-fault pthreads


【解决方案1】:

首先,您应该使用PTHREAD_MUTEX_INITIALIZER 初始化mutex 变量。

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

或者你可以从主线程调用pthread_mutex_init(&amp;lock,0)来初始化lock

第二件事,替换下面的语句

 int* y = (int*) x;

 int* y = (int*) &x;

因为y 应该有valid address 否则你不能稍后执行*y(就像你正在做的那样)

希望对你有帮助。

【讨论】:

  • @ShahzaibRahim 立即查看。
【解决方案2】:

中的多个指针问题

void* addcounter(void* threadid) { 
  pthread_mutex_lock(&lock);
  int* id = (int*)threadid + 1;    // <== A
  int* y = (int*)x;                // <== B
  int total = (*id) * (*y);        // <== C
  int i = 0;
  for (i = 0; i < total; i++) {
    counter += 1;
  }
  pthread_mutex_unlock(&lock);
}

解释

  • 答:大概int id = *(int *)threadid + 1;
  • B:int *y = (int *)x 将把 y 指针设置为 x... int 危险!可能是int y = x; (?)
  • C: 然后修复总的int total = id + y;(下面循环不用,counter += total;就够了

【讨论】:

    猜你喜欢
    • 2016-02-03
    • 2014-08-04
    • 2012-11-19
    • 1970-01-01
    • 2015-06-25
    • 2021-06-03
    相关资源
    最近更新 更多