我正在尝试使用多线程程序,但 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;
}
最佳答案
sum1
和 sum2
未初始化。所以这些行
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/