【发布时间】:2021-05-11 02:06:00
【问题描述】:
如果我连续调用 pthread_join(不使用其他函数)会导致分段错误。
我可以通过在两次 pthread_join 调用之间插入 sleep();、printf() 或其他任何内容来解决问题。
操作系统和 GCC 版本:
gcc --version
gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
编译命令:
gcc demo_thread.c -lpthread -o demo_thread.out
源码(demo_thread.c):
#include <stdio.h>
#include <stdlib.h>
void *f1(void *);
int main() {
int k = 2;
pthread_t fa[k];
for(int i=0; i<k; i++) {
pthread_create(&fa[i], NULL, f1, NULL);
}
for(int i=0; i<k; i++) {
// printf("%ul\n", fa[i]); // uncomment this line, problem disapper.
pthread_join(fa[i]);
}
}
void *f1(void *arg) {
for(int i=0; i<4;i++) {
printf("%d\n",i );
}
return 0;
}
【问题讨论】:
-
始终检查您的错误返回。如果
pthread_create失败,它不会将您的fa[i]设置为任何有效值。我想您必须将k设置得非常高,因为只要 k = 2,这里就没有问题。 -
我只设置了 k = 2。我可以确保调用
pthread_create成功。
标签: c linux fault continuous pthread-join