微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用一个参数调用 pthread_join 会导致分段错误吗?

如何解决使用一个参数调用 pthread_join 会导致分段错误吗?

如果我连续调用 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;
}

解决方法

你是怎么编译的?我刚刚意识到您没有使用 #include <pthread.h> 并且您为 pthread_join 使用了一个参数而不是两个。

如果我省略了我得到的包含

error: unknown type name ‘pthread_t’

如果我确实包含它,那么我得到

error: too few arguments to function ‘pthread_join’

哦,我明白了,如果我包含 #include <stdlib.h> 并省略 <pthread.h>,那么它会有 pthread_t 的定义,但 pthread_join 没有任何定义。不过还是有很多警告:

warning: implicit declaration of function ‘pthread_join’

您应该始终使用编译器的 -Wall -W -pedantic 参数构建程序。并修复警告。

并解释崩溃:由于您没有将 NULL 作为第二个参数传递给 pthread_join,它将接收一个“随机”值,然后将其写入,就好像它是一个指针一样。它不是。因此,它要么将一个值写入您分配的内存中不应写入的值,要么会出现分段错误。

并解释 printfsleep 如何解决问题:进行这些函数调用必须改变 RSI 寄存器的值(RSI 用于第二个函数参数)足以使它是一个有效的指针或 NULL。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。