[英]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
的線程啟動 function必須采用單個void *
參數。
由於您要傳入多個結構,因此您需要定義一個附加結構,其中包含線程 function 預期的所有數據並傳遞一個指向該結構的指針。
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]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.