pthread_join导致分段错误(简单程序)

kei*_*ter 0 c multithreading pthreads segmentation-fault pthread-join

我只是尝试使用多线程程序,但我遇到了pthread_join函数的问题.下面的代码只是一个我用来显示pthread_join崩溃的简单程序.此代码的输出将是:

before create

child thread

after create

Segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud)

什么原因导致pthread_join给出分段错误?

#include <pthread.h>
#include <stdio.h>

void * dostuff() {
    printf("child thread\n");
    return NULL;
}

int main() {
    pthread_t p1;

    printf("before create\n");
    pthread_create(&p1, NULL, dostuff(), NULL);
    printf("after create\n");

    pthread_join(p1, NULL);
    printf("joined\n");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 6

因为在你的调用中pthread_create实际调用了函数,并且因为它返回NULL pthread_create将失败.这将无法正确初始化p1,因此(可能)会导致pthread_join调用中的未定义行为.

要解决此问题,请将函数指针传递给pthread_create调用,不要调用它:

pthread_create(&p1, NULL, dostuff, NULL);
/* No parantehsis --------^^^^^^^ */
Run Code Online (Sandbox Code Playgroud)

这也应该教你检查函数调用的返回值,因为pthread_create失败时会返回非零值.

  • 但是OP的'dostuff`函数的类型错误! (3认同)

Ker*_* SB 5

您需要修复函数类型和调用方式pthread_create:

void * dostuff(void *) { /* ... */ }
//             ^^^^^^
Run Code Online (Sandbox Code Playgroud)

pthread_create(&p1, NULL, dostuff, NULL);
//                        ^^^^^^^
Run Code Online (Sandbox Code Playgroud)