我已经完成了以下代码。
#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 = %dn", f->a, f->b); //Line1
err = pthread_join(tid2, &ret);
if(err != 0 )
{
perror("pthread_join2");
exit(-1);
}
printf("ret = %dn", *(int*)ret); //Line2
return 0;
}
我在第 2 行上遇到分段错误。2号线有什么问题
如果我将第 2 行修改为
printf("ret = %d", (int)ret);
没有分段错误,它打印正确的值(即 100)。我不明白为什么修改有效。我相信我对双指针的使用有错误的概念。我想纠正它。
分段错误的原因是什么,为什么修改有效?
这是因为您返回的是实际整数,而不是指针,但您将其作为指针访问。
从线程返回一个数字。在第一个线程中,该数字是一个struct foo *
。因此,如果你说
pthread_join(tid1, &ret);
然后ret
将包含该指针(不是双指针)。
同样,在第二种情况下,即使您将其视为void *
,您也会返回100
。尽管如此,价值仍然100
!
因此,当您编写时
pthread_join(tid2, &ret);
ret
将包含 100
,它不是一个指针,而只是一个整数。这就是为什么您也应该将其投射到int
。
您遇到分段错误的原因是您将100
视为int *
,然后尝试取消引用它。
>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
返回值的类型转换在这里是多余的,可以省略。
这个问题还可以帮助您: 完成后关闭线程
这是因为您正在尝试取消引用地址为 100 的指针。
与其查看返回值,不如传入指向要在thread_funcs中分配的内容的指针?也就是说,使用 thread_func1() 和 thread_func2() 的 "void *arg" 参数
喜欢这个:
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 = %dn", f->a, f->b); //Line1
...
printf("ret = %dn", ret); //Line2
...
}