0

我已经完成了以下代码。使用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)。我不明白为什么修改可行。我相信我有关于使用双指针的错误概念。我想要纠正它。

分段错误的原因是什么以及修改的原因是什么?

+0

旁注:使用'malloc'这样的:'结构FOO * TEMP =的malloc(的sizeof(*温度));'当你理解了好处,你会欣赏它。 – Shahbaz

+0

与您的问题无关,但不释放第一个线程函数返回的值。 –

+0

@JoachimPileborg:点注意!在使用f-> a和f-> b访问值之后,'free'必须完成吗? –

回答

2

您从线程返回一个数字。在第一个线程中,该号码是struct foo *。因此,如果你说

pthread_join(tid1, &ret); 

然后ret将包含指针(这是双指针)。

类似地,在第二种情况下,即使您正在查看它,就好像它是void *一样,即将返回100。尽管如此,价值仍然是100

因此,当你写

pthread_join(tid2, &ret); 

ret将包含100,这不是一个指针,但仅仅是整数。这就是为什么你也应该把它投到int

您遇到分段错误的原因是您将100视为int *,然后尝试对其进行解引用。

3

这是因为你正在返回实际的整数,而不是一个指针,但你可以作为指针访问它。

+1

+1伟大的思想想象,你打败了我14秒:) – Brady

+1

@Brady是啊也许... :)但你的答案包含一个替代解决方案。 –

1

它,因为你想dereferencce的指针,其地址为100

而不是看的返回值,你为什么不一个指针,要在thread_funcs分配传递什么?也就是说,使用thread_func1的 “无效* ARG” 参数()和thread_func2()

像这样:

void* thread_func1(void *arg) 
{ 
    struct foo **fooPtrPtr = (struct foo**) arg; 
    *fooPtrPtr = (struct foo*)malloc(sizeof(struct foo)); 

    ... 
} 

void* thread_func2(void *arg) 
{ 
    int *intPtr = arg; 
    *intPtr = 100; 
    ... 
} 

int main() 
{ 
    pthread_t tid1, tid2; 
    int err; 
    struct foo *f; 
    int ret; 

    err = pthread_create(&tid1, NULL, thread_func1, &f); 
    err = err | pthread_create(&tid2, NULL, thread_func2, &ret); 
    ... 
    printf("a = %d, b = %d\n", f->a, f->b); //Line1 
    ... 
    printf("ret = %d\n", ret); //Line2 
    ... 
} 
1

pthread_exit((void*)100);导致整数100成为您线程的退出状态。它只是滥用类型转换,因此void*是它的类型。 如果你想取出这个值,你将不得不在主线程中使用同一类型转换滥用,以及:

int ret; 
err = pthread_join(tid2, (void**) &ret); 
// here you can work with ret as with any other integer 

我也建议你使用return,而不是pthread_exit。另请注意,使用malloc动态分配的内存应通过调用free来释放。而且这里的malloc返回值的类型重复是冗余的,可以省略。

这个问题也可以帮助你:Close a thread when done with it