235711131719
235711131719

Reputation: 37

Passing Entire Array of Structs to Pthread_Create in C

I am having a bit of trouble with this one issue. I have an array that holds 2 structs. I need to pass that array into a thread function and be able to access and manipulate both structs in that array. All the examples I've looked at and found typically pass each element of the array to pthread_create, but in the context of my program, I can only call one instance of pthread_create at a time, so I cannot pass each element in the array one by one. Here is the simplified code I am looking at right now (let me know if you need more relevant information):

typedef struct foo
{
    int a;
    char b[100];
}foo;


void *threadFunction(void *arr);
.
.
.
int main(int argc, char *argv[])
{
    foo temp1, temp2;
    //Somewhere between here temp1 and temp2 are initialized and filled
    foo arr[2];
    arr[0] = temp1;
    arr[1] = temp2;
    pthread_create(&thread, &attr, threadFunction, (void *)arr);
.
.
.
}
void *threadFunction(void *arr)
{       
    foo *temp = (foo *)malloc(2 * sizeof(foo));
    temp = (foo *)arr;
    .
    .
    .
    free(temp);
    pthread_exit(NULL);
}

I also tried just saying

foo *temp = (foo *)arr;

The obvious solution was to assign each element in temp[] to an element in arr[] but that doesn't work.

The result is I only have access to the first element in the temp array, even if I try to access temp[1], which makes sense since it doesn't appear that I am assigning the 2nd element in arr[] to anything.

I'm sure I'm missing something obvious, but I can't seem to find it, and I haven't been able to find any relevant information about this specific situation. Thanks for any help.

Upvotes: 1

Views: 3761

Answers (1)

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43498

It involves casting the void pointer to the pointer type of your struct, and then dereferencing that pointer expression to get the element at a particular offset:

*((foo *) arr); /* first element */
*((foo *) arr + 1); /* second element */

Edit: another important issue - the arr array has to be defined globally, outside of main. Because the newly created thread will have its own stack space, it's not very safe to access another thread's stack.

Upvotes: 1

Related Questions