简体   繁体   中英

How do i pass a struct as an argument in pthread in c

How do i pass a struct as an argument in pthread in c

    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);

i have tried calling it as so with no result

    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);

A thread start function passed to pthread_create must take a single void * argument.

Since you're passing in multiple structs, you'll need to define an additional struct which contains all data expected by the thread function and pass a pointer to that.

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM