Search code examples
cmultithreadingsegmentation-faultpthreadspthread-join

Segmentation fault (core dumped) after pthread_join


I am trying to work with multi-threaded programs, and I am getting an error with the pthread_join function. The output from this code is:

after pthread_create
Segmentation fault (core dumped)

And here is the code:

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

void *myfunc1()
{
    // code segments
    pthread_exit(sum1);            
}

void *myfunc2()
{
    // code segments    
    pthread_exit(sum2);     
}


int main(int argc, char *argv[])
{

    void *sum1, *sum2;
    pthread_t thread_id1,thread_id2;

    pthread_create(&thread_id1,NULL,myfunc1,NULL);
    pthread_create(&thread_id2,NULL,myfunc2,NULL);
printf("after pthread_create\n");
    pthread_join(thread_id1, &sum2);
    pthread_join(thread_id2, &sum1);
printf("after pthread_join\n");
    float firstSum = *((float *)sum1);
    float secondSum = *((float *)sum2);

    printf("Sum is %.5f\n\n", firstSum+secondSum);
    return 0;
}

Solution

  • sum1 and sum2 are not initialised. So these lines

    float firstSum = *((float *)sum1);
    float secondSum = *((float *)sum2);
    

    dereference undefined pointers.

    Your thread functions should pass a pointer back (to something that survives the exit of the function) which can then be used by pthread_join e.g.

    void *myfunc1()
    {
        float *ret = malloc(sizof *ret);
        *ret = 3.14;
        // code segments
        pthread_exit(ret);            
    }
    

    Then in main

    float *sum1;
    
    // run the thread
    
    pthread_join(thread_id2, (void**)&sum1); 
    
    float result = *sum1;
    free(sum1);