我已經完成了以下代碼。使用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'必須完成嗎? –