我已经完成了以下代码。使用pthread_exit()访问返回值
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
struct foo
{
int a;
int b;
};
void* thread_func1(void *arg)
{
struct foo *temp = (struct foo*)malloc(sizeof(struct foo));
temp->a = 10;
temp->b = 20;
pthread_exit(temp);
}
void* thread_func2(void *arg)
{
pthread_exit((void*)100);
}
int main()
{
pthread_t tid1, tid2;
int err;
struct foo *f;
void *ret;
err = pthread_create(&tid1, NULL, thread_func1, NULL);
err = err | pthread_create(&tid2, NULL, thread_func2, NULL);
if(err != 0)
{
perror("pthread_create()");
exit(-1);
}
err = pthread_join(tid1, (void**)&f);
if(err != 0)
{
perror("pthread_join1");
exit(-1);
}
printf("a = %d, b = %d\n", f->a, f->b); //Line1
err = pthread_join(tid2, &ret);
if(err != 0)
{
perror("pthread_join2");
exit(-1);
}
printf("ret = %d\n", *(int*)ret); //Line2
return 0;
}
我在Line2上出现分段错误。什么是错线2
如果我修改线路2至
的printf( “RET =%d \ n” 个,(int)的RET);
没有分段错误,它打印正确的值(即100)。我不明白为什么修改可行。我相信我有关于使用双指针的错误概念。我想要纠正它。
分段错误的原因是什么以及修改的原因是什么?
旁注:使用'malloc'这样的:'结构FOO * TEMP =的malloc(的sizeof(*温度));'当你理解了好处,你会欣赏它。 – Shahbaz
与您的问题无关,但不释放第一个线程函数返回的值。 –
@JoachimPileborg:点注意!在使用f-> a和f-> b访问值之后,'free'必须完成吗? –