Pergunta

I am just trying to work with multi-threaded programs, but I am having problems with the pthread_join function. The code below is just a simple program I am using to show pthread_join crashing. The output from this code will be:

before create

child thread

after create

Segmentation fault (core dumped)

What causes pthread_join to give a segmentation fault?

#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;
}
Foi útil?

Solução

Because in your call to pthread_create you actually call the function, and as it returns NULL pthread_create will fail. This will not properly initialize p1 and so will (probably) cause undefined behavior in the pthread_join call.

To fix this pass the function pointer to the pthread_create call, do not call it:

pthread_create(&p1, NULL, dostuff, NULL);
/* No parantehsis --------^^^^^^^ */

This should also teach you to check the return values of function calls, as pthread_create will return non-zero on failure.

Outras dicas

You need to fix your function type and the way you call pthread_create:

void * dostuff(void *) { /* ... */ }
//             ^^^^^^

pthread_create(&p1, NULL, dostuff, NULL);
//                        ^^^^^^^
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top