[SOLVED] How do I pass a struct as an argument in pthread in c?

Issue

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

Solution

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

Answered By – dbush

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.