如何在 c 中的 pthread 中将结构作为参数传递?
How do I pass a struct as an argument in pthread in c?
如何在 c:
中的 pthread 中将结构作为参数传递
void * aFunction (aStruct1 *theStruct1, aStruct2 *theStruct2, aStruct3 *theStruct3){
printf("%s", theStruct1->text);
}
pthread_t thread[2];
pthread_create(&thread[0], NULL, aFunction, "how do i pass all the struct argument here (theStruct1, theStruct2 , theStruct3)");
pthread_create(&thread[1], NULL, aFunction, "how do i pass all the struct argument here (theStruct1, theStruct2 , theStruct3)");
pthread_join(thread[1],NULL);
pthread_join(thread[2],NULL);
我试过这样调用它,但没有结果:
void * aFunction (aStruct1 *theStruct1, aStruct2 *theStruct2, aStruct3 *theStruct3){
printf("%s", theStruct1->text);
}
pthread_t thread[2];
pthread_create(&thread[0], NULL, aFunction(theStruct1, theStruct2 , theStruct3), NULL);
pthread_create(&thread[1], NULL, aFunction(theStruct1, theStruct2 , theStruct3), NULL);
pthread_join(thread[1],NULL);
pthread_join(thread[2],NULL);
传递给 pthread_create
的线程启动函数 必须 接受一个 void *
参数。
由于您要传入多个结构,因此您需要定义一个额外的结构,其中包含线程函数所需的所有数据,并传递指向该结构的指针。
struct thread_args {
aStruct1 *s1;
aStruct2 *s2;
aStruct3 *s3;
};
void *aFunction (void *p){
struct thread_args *args = p;
printf("%s", args->s1->text);
return NULL;
}
struct thread_args args[] = {
{ theStruct1, theStruct2, theStruct3 },
{ theStruct1, theStruct2, theStruct3 }
};
pthread_create(&thread[0], NULL, aFunction, &args[0]);
pthread_create(&thread[0], NULL, aFunction, &args[1]);
如何在 c:
中的 pthread 中将结构作为参数传递 void * aFunction (aStruct1 *theStruct1, aStruct2 *theStruct2, aStruct3 *theStruct3){
printf("%s", theStruct1->text);
}
pthread_t thread[2];
pthread_create(&thread[0], NULL, aFunction, "how do i pass all the struct argument here (theStruct1, theStruct2 , theStruct3)");
pthread_create(&thread[1], NULL, aFunction, "how do i pass all the struct argument here (theStruct1, theStruct2 , theStruct3)");
pthread_join(thread[1],NULL);
pthread_join(thread[2],NULL);
我试过这样调用它,但没有结果:
void * aFunction (aStruct1 *theStruct1, aStruct2 *theStruct2, aStruct3 *theStruct3){
printf("%s", theStruct1->text);
}
pthread_t thread[2];
pthread_create(&thread[0], NULL, aFunction(theStruct1, theStruct2 , theStruct3), NULL);
pthread_create(&thread[1], NULL, aFunction(theStruct1, theStruct2 , theStruct3), NULL);
pthread_join(thread[1],NULL);
pthread_join(thread[2],NULL);
传递给 pthread_create
的线程启动函数 必须 接受一个 void *
参数。
由于您要传入多个结构,因此您需要定义一个额外的结构,其中包含线程函数所需的所有数据,并传递指向该结构的指针。
struct thread_args {
aStruct1 *s1;
aStruct2 *s2;
aStruct3 *s3;
};
void *aFunction (void *p){
struct thread_args *args = p;
printf("%s", args->s1->text);
return NULL;
}
struct thread_args args[] = {
{ theStruct1, theStruct2, theStruct3 },
{ theStruct1, theStruct2, theStruct3 }
};
pthread_create(&thread[0], NULL, aFunction, &args[0]);
pthread_create(&thread[0], NULL, aFunction, &args[1]);