ahabos
ahabos

Reputation: 207

Passing an array of structs to a pthread_create

So I have a struct as follows:

struct threadData{
    string filename
    int one;
    int two;
};

and I created an array of these structs like this:

pthread_t threadID[5];
struct threadData *threadP;
threadP = new struct threadData[5];

then I'm passing this array of structs to a thread function as follows:

for(int i = 0; i < 5; i++){
    pthread_create(&threadID[i], NULL, threadFunction, (void * ) threadP[i]);
}

and this is how my threadFunction is written:

void *threadFunction(void * threadP[]){

}

I've tried various things, but I always get the error that what I pass in is not correct, how do I do this properly so that I can access and process the variables in each struct object I pass in? I have a feeling that my syntax somewhere is wrong due to me using an array of structs...I just don't know where or what exactly is wrong. Any help would be appreciated!

Upvotes: 0

Views: 1641

Answers (1)

Jonathan Wakely
Jonathan Wakely

Reputation: 171491

void *threadFunction(void * threadP[]){

Functions cannot have parameters of array types in C++, instead the parameter has to be a pointer, and an array used as a function argument decays to a pointer to the first element, so that declaration is equivalent to:

void *threadFunction(void ** threadP){

Which clearly isn't the right type to pass to pthread_create

You need to pass a function with this signature:

void *threadFunction(void * threadP)

Upvotes: 1

Related Questions