【发布时间】: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