#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
pthread_t id1,id2;
struct arg{int a[2];}*p;
void *sum(void *args)
{
struct arg *b=((struct arg*)args);
printf("hello:%d%d",b->a[0],b->a[1]);
}
void *mul(void *args)
{
struct arg *c=((struct arg*)args);
printf("hi:%d%d",c->a[0],c->a[1]);
}
main()
{
int err1,err2;
p->a[0]=2;
p->a[1]=3;
err1=pthread_create(&id1,NULL,&sum,(void*)p);
err2=pthread_create(&id2,NULL,&mul,(void*)p);sleep(5);
}
我正在尝试使用结构将数据传递给线程......但我总是遇到段错误......任何人都可以告诉我我的代码有什么问题......
最佳答案
您遇到段错误是因为您没有为p
分配内存;它尝试将值分配给内存地址 0,这会导致段错误。
尝试使用 malloc 分配内存:
main()
{
int err1,err2;
struct arg *p=(struct arg *)malloc(sizeof(struct arg));
p->a[0]=2;
p->a[1]=3;
err1=pthread_create(&id1,NULL,&sum,(void*)p);
err2=pthread_create(&id2,NULL,&mul,(void*)p);sleep(5);
}
关于c - 线程传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26200184/