【发布时间】:2016-09-13 21:09:10
【问题描述】:
我正在 Linux 系统上使用线程做一些第一步,我有这个错误发生在一个程序的基础上,该程序获取了一些 n 参数并创建了 n 线程数。
这是代码的重要部分:
线程应该运行的函数:
void* function(void* arg){
int id = (long)arg;
printf("Thread #%ld created!\n",id);
pthread_exit(0);
}
main 函数中的重要部分代码
int main(int argc, char **argv){
if(argc != 3){
printf("Usage: %s <num> <exp>\n",argv[0]);
exit(-1);
}
int num = atoi(argv[1]), exp = atoi(argv[2]);
long i;
pthread_t threads[num];
pthread_attr_t attr;
printf("Creating %d threads \n",num);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
for (i = 0; i < num; i++) {
pthread_create(&threads[i],&attr,function,(void*)i);
}
pthread_attr_destroy(&attr);
for (i = 0; i < num; i++) {
printf("Thread #%d is %ld\n", i, threads[i]);
}
for (i = 0; i < num; i++) {
pthread_join(threads[num], NULL);
}
}
请注意最后一个带有pthread_join 函数的for 循环,当我将其注释掉时,程序结束正常(退出代码0),但输出显然是错误的,因为并非所有线程都在之前运行function主进程退出。
如果我不注释掉它,我会在尝试使用我的 Linux 操作系统中的终端运行时得到 segmentation fault (core dumped),而在我的 IDE (CLion) 中运行时得到Process finished with exit code 139。
我找不到我做错了什么,因为它是一个非常基本的程序,应该没有什么难找的东西,是什么问题导致了错误?
【问题讨论】:
-
提示:“segmentation fault”和“Process finished with exit code 139”是同义词。 139 = 0x80 | 11,这是当 shell 执行的程序被信号 11,分段错误终止时,shell 作为退出代码返回的内容。
标签: c linux multithreading pthreads pthread-join