首页 > 解决方案 > pthread_join 不断导致段错误

问题描述

这个问题绝对是一个愚蠢错误的根源,但对于我的生活,我无法深入了解它。

我正在编写一个更大的程序,但我已经缩小了每当我调用pthread_join. 我在下面包含了相关代码,希望有人可以帮助我找出我做错了什么。干杯:)

用于管理 pthread 的函数

void *scalloc(size_t nmemb, size_t size)
{
  void *p;
  p = calloc(nmemb, size);
  if (p == NULL)
    sys_error("Error allocating memory block (calloc).", 1);
  return p;
}

pthread_t *new_thread_array(int n)
{
  return scalloc(n, sizeof(pthread_t));
}

int spthread_create(pthread_t *thread, const pthread_attr_t *attr,
            void *(*start_routine) (void *), void *arg)
{
  int ret;
  if ((ret = pthread_create(&thread, attr, start_routine, arg)) != 0)
    sys_error("Error at pthread_create.", ret);
  return 0;
}

int spthread_join(pthread_t thread, void **retval)
{
  int ret;
  if ((ret = pthread_join(thread, retval)) != 0)
    sys_error("Error at pthread_join.", ret);
  return 0;
}

int create_threads(pthread_t *thread_arr, int n, const pthread_attr_t *attr,
           void *(*start_routine) (void *), void **arg_arr)
{
  for (int i = 0; i < n; i++) {
    spthread_create(&thread_arr[i], attr, start_routine, arg_arr[i]);
    debug("created thread %d", i);
  }
  return 0;
}

int join_threads(pthread_t *thread_arr, int n, void **ret_arr)
{
  debug("Starting join");
  for (int i = 0; i < n; i++) {
    if (ret_arr != NULL)
      spthread_join(thread_arr[i], ret_arr[i]);
    else {
      debug("Attempting to join %d", i);
      spthread_join(thread_arr[i], NULL);
      debug("Joined %d", i);
    }
  }
  return 0;
}

产生错误的测试代码

void *threadfunc(void *id)
{
  fflush(stdout);
  fprintf(stdout, "Thread %d printing.\n", *(int *)id);
  fflush(stdout);
  return;
}

int threadtest(int nodes)
{
  int ret;
  int *targs = scalloc(nodes, sizeof(int));
  int *pass[nodes];
  for (int i = 0; i < nodes; i++) {
    targs[i] = i;
    pass[i] = &targs[i];
  }

  printf("Starting L1 thread test...\n");
  pthread_t *threads = new_thread_array(nodes);
  debug("Allocated pthread array for %i threads.", nodes);

  create_threads(threads, nodes, NULL, &threadfunc, pass);
  join_threads(threads, nodes, NULL);
  debug("Successfully joined %i threads.", nodes);
  free(targs);
  free(threads);
  return 0;
}

int main()
{
  return threadtest(5);
}

最后,这是运行函数的输出threadtest,确认段错误(出现)发生在父线程中,在调用pthread_join.

Starting L1 thread test...
Allocated pthread array for 5 threads.
created thread 0
created thread 1
Thread 0 printing.
created thread 2
Thread 1 printing.
Thread 2 printing.
created thread 3
Thread 3 printing.
created thread 4
Thread 4 printing.
Starting join
Attempting to join 0
zsh: segmentation fault  ./tests/L1tests

标签: cunixpthreadsdistributed-computing

解决方案


推荐阅读