【问题标题】:Segmentation fault (exit code 139) when using pthread_join使用 pthread_join 时出现分段错误(退出代码 139)
【发布时间】: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


【解决方案1】:

您应该使用pthread_join(threads[i], NULL); 而不是pthread_join(threads[num], NULL);。假设,num 通过参数设置为 4。然后threads[num] 指向不存在的数组的第 5 个元素,因为您分配了一个只有 4 个元素的数组。

【讨论】:

  • 好尴尬...没注意到,愚蠢的我...谢谢!
猜你喜欢
  • 2017-01-20
  • 1970-01-01
  • 2021-04-16
  • 2019-08-11
  • 2022-01-11
  • 2016-09-15
  • 1970-01-01
  • 2018-12-12
  • 2019-08-25
相关资源
最近更新 更多