0

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;
}
Ali Hüseyin
  • 13
  • 1
  • 4

2 Answers2

2

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);
JeremyP
  • 84,577
  • 15
  • 123
  • 161
0

Your segmentation fault happens in one of your threads. pthread_create() creates and launches your thread, pthread_join() makes your main thread wait for the end of the other threads. Your main thread keeps running and starts waiting for your other threads to end, but one of them creates a segmentation fault so your main thread does not display "after pthread_join". So the segmentation fault does not come from pthread_join().

JeremyP
  • 84,577
  • 15
  • 123
  • 161
Silveris
  • 1,048
  • 13
  • 31
  • 1
    Nope. That's not the cause of the issue at all. Especially considering all the threads do nothing. – JeremyP Apr 20 '17 at 10:03
  • On reflection, the down vote was harsh because the question omits details from the threads that is probably important, so I have retracted it. – JeremyP Apr 20 '17 at 10:14