【问题标题】:C - pthread_join() hangs (sometimes)C - pthread_join() 挂起(有时)
【发布时间】:2016-09-19 08:47:58
【问题描述】:

各位程序员们好,

我想用 pthread 用 C 语言编写一个简单的多线程程序,但不知何故 pthread_join 似乎挂起。 它似乎并不总是发生,有时一切都运行良好,下次它不会再次挂起,通常在第一个线程上。

我已经将代码最小化到最低限度,这样我就可以排除其他问题了。当然,在完整的代码中,线程做了一些计算。但是即使代码非常精简,问题仍然存在。并且在不止一台机器上使用不同的操作系统。

strace 告诉我挂起与 FUTEX_WAIT 有关,完整的最后几行:

write(1, "Joining Thread 0...\n", 20Joining Thread 0...
)   = 20
futex(0x7fff61718a20, FUTEX_WAIT, 1634835878, NULL

我尝试使用 gdb 对其进行调试,但我糟糕的调试仍然非常有限,尤其是对于多线程程序。 我还尝试使用不同的 C 标准(C99 和 Ansi)和两个 pthread 参数(-lpthread、-pthread)来编译它,但问题仍然存在。

(简化的)代码monte2.c:

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

void *monte(struct MonteArgs *args) {
  pthread_exit(NULL);
}

int main(int argc, char **argv) {

  int numThreads, numSamples;
  int i;

  if (argc != 3) {
    printf("Usage: monte threads samples\n");
    exit(1);
  }

  numThreads = atoi(argv[1]);
  pthread_t threads[numThreads];
  numSamples = atoi(argv[2]);

  for (i=0; i<numThreads; i++) {
    if (pthread_create(&threads[i], NULL, monte, NULL)) {
      printf("Error Creating Thread %d!\n", i);
      return 1;
    }
  }

  for (i=0; i<numThreads; i++){
    printf("Joining Thread %d...\n", i);
    pthread_join(&threads[i], NULL);
  }

  printf("End!\n");
  fflush(stdout);
  return(0);
}

我用编译

gcc monte2.c -lpthread -o monte

并使用

运行
./monte2 3 100

其中第一个参数是线程数,而第二个参数实际上对于缩减的代码是不需要的。

【问题讨论】:

  • 使用 PTreads 编译代码时要添加-pthread

标签: c multithreading gcc pthreads


【解决方案1】:

自从我完成多线程 C 以来已经有一段时间了,但你不应该忽略编译器警告 :-)。使用-Wall 编译。

您应该会看到如下警告:

note: expected 'pthread_t' but argument is of type 'pthread_t *'
int       WINPTHREAD_API pthread_join(pthread_t t, void **res);

当你应该传递pthread_t时,你传递了pthread_t*

参考pthread_join 文档:http://man7.org/linux/man-pages/man3/pthread_join.3.html

【讨论】:

  • 谢谢你! :-) 这个简单的事情解决了它。我觉得很奇怪它并不总是发生,我只是没有看到它,因为我用其他简单的例子交叉检查了我的简化程序,他们通常这样做完全一样。 .
猜你喜欢
  • 2018-09-05
  • 2020-02-25
  • 2018-12-13
  • 2020-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-02
相关资源
最近更新 更多