定义结构
typedef struct {
int a,b;
}targ;
第一个线程函数:
void* sum(void *arg) {
int *s;
targ *p = (targ*)arg;
int i=p->a;
int j=p->b;
*s=i+j;
pthread_exit((void*)s);
}
第二个线程函数:
void* pdt(void *arg) {
int *p;
targ *s= (targ*)arg;
int i=s->a;
int j=s->b;
*p=i*j;
pthread_exit((void*)p);
}
主线程函数:
int main(void) {
int ret1,ret2;
pthread_t tid1,tid2;
targ *x;
x=(targ*)malloc(sizeof(targ));
printf("enter the 2 numbers\n");
scanf("%d%d",&x->a,&x->b);
printf("%d%d",x->a,x->b);
pthread_create(&tid1,NULL,sum,(void*)x);
pthread_create(&tid2,NULL,pdt,(void*)x);
pthread_join(tid1,(void**)&ret1);
pthread_join(tid2,(void**)&ret2);
printf("the sum and product of the 2 numbers is %d and %d\n",(int)ret1, (int)ret2);
return 0;
}
尽管我已按照每个 API 的手册页面进行操作,但我无法理解为什么会出现段错误。
该程序旨在了解线程函数如何相互协作。主函数将值传递给每个线程函数,然后它们将值返回给主函数。
最佳答案
您尚未为 s 和 p 指针变量分配内存。所以发生了段错误。 您应该分配内存或仅使用地址。
关于c - C中的线程管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36457002/