1

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;
}
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
keithbhunter
  • 12,258
  • 4
  • 33
  • 58
  • 2
    Are you sure you've enabled and listened to all your compiler warnings? This looks like a lot of avoidable mistakes. – Kerrek SB Apr 18 '13 at 13:08

2 Answers2

7

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
5

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

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

pthread_create(&p1, NULL, dostuff, NULL);
//                        ^^^^^^^
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084