主线程传实参给子线程后,主线程退出,这时候如果参数实在主线程启动时才定义的,那么主线程退出,传给子线程的参数也失效了。
解决方法
参数定义为全局变量,传到子线程时,再开一个变量接收保存这个参数
static int a;
void *pthread(int *a)
{
int b;
b=*(*a);
}
还一种方法就是在主线程开辟一片内存空间,存储变量,在子线程用完了在释放
struct test
{
int c;
int d;
};
void *test_func(struct test *a)
{
free(a);
}
void main(void)
{
.........
struct test *a;
a=malloc(sizeof(struct test));
pthread_create(&thread, NULL, test_func,a);
.........
}
第一种是可行的,第二种没有实践