c - pthread_join 后出现段错误(核心转储)

标签 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;
}

最佳答案

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

然后在main中

float *sum1;

// run the thread

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

float result = *sum1;
free(sum1);

关于c - pthread_join 后出现段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43515890/

相关文章:

python - 如何在 Python 中使用锁来保护对象?

java - 终止 Future 并获得中间结果

c - 小段代码出现段错误(核心转储)错误

c - 我的 C 代码遇到 sigsegv 错误

c++ - 多线程单读单写fifo队列

c - 矩阵声明上的 SIGSEGV

c - 我怎样才能循环一个字符串?

c++ - 如何使用 vtkImageImport 创建在删除 vtkImageImport 后仍然存在的 vtkImageData?

c - 有没有办法知道在 Linux 中传递给 __free_hook 的指针的大小?

c - 在 C : Unhandled exception : 0xC0000005: Access violation writing location. 程序不会运行