pthread_join之后的分段错误(核心转储)

时间:2017-04-20 09:44:08

标签: c multithreading segmentation-fault pthreads pthread-join

我正在尝试使用多线程程序,我收到了pthread_join函数的错误。此代码的输出为:

after pthread_create
Segmentation fault (core dumped)

以下是代码:

#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;
}

2 个答案:

答案 0 :(得分:2)

sum1sum2未初始化。所以这些行

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

取消引用未定义的指针。

你的线程函数应该返回一个指针(返回到函数退出后的某个东西)然后pthread_join可以使用它。例如。

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

然后在主

float *sum1;

// run the thread

pthread_join(thread_id2, (void**)&sum1); 

float result = *sum1;
free(sum1);

答案 1 :(得分:0)

您的分段错误发生在您的某个主题中。 pthread_create()创建并启动你的线程,pthread_join()使你的主线程等待其他线程的结束。您的主线程继续运行并开始等待其他线程结束,但其中一个线程会创建一个分段错误,因此您的主线程不会在pthread_join&#34;之后显示#34;。因此,分段错误不是来自pthread_join()。