以下代码为第二种情况提供了seg错误,但对于第一种情况,它工作正常。但他们俩都在做同样的事情。这里pthread_join()调用没有产生任何错误,但是当从pthread_join()打印响应时,它会生成Segmentation fault。第一个人做的与第二个不同?而第二个实际上是错的?
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void * thread_ops(void *arg){
printf("Thread Start!\n");
int val=((int *)arg)[0];
printf("value at thread -> %d\n",val);
int * c=(int *)malloc(sizeof(int *));
*c=val;
pthread_exit((void*)c);
}
int main(){
pthread_t pt,pt2;
pthread_attr_t ptatr;
int ar[1]={1};
// working
pthread_attr_init(&ptatr);
int status;
status=pthread_create(&pt,&ptatr,&thread_ops,ar);
printf("Thread Stats : %d\n",status);
int *result;
pthread_join(pt,(void **)&result);
printf("Result is %d\n",*result);
// why does the next set of lines generate seg fault ??
void **result2;
status=pthread_create(&pt,&ptatr,&thread_ops,ar);
pthread_join(pt,result2);
int ** res2=(int **)result2;
printf("Result is %d\n",**res2);
return 0;
}
Thread Stats : 0
Thread Start!
value at thread -> 1
Result is 1
Thread Start!
value at thread -> 1
Segmentation fault (core dumped)
答案 0 :(得分:1)
而不是
void **result2;
pthread_join(pt,result2);
使用
void *pvresult;
pthread_join(pt, &pvresult);
并且正如您所期望的那样int
添加以下内容:
int result = *((int*) pvresult);
以这种方式打印:
printf("Result is %d\n", result);
同时替换此
int * c=(int *)malloc(sizeof(int *));
由此
int *c = malloc(sizeof *c);