首页 > 解决方案 > 使用一个参数调用 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;
}

标签: clinuxfaultcontinuouspthread-join

解决方案


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


推荐阅读