Reputation: 2983
Apologies for this being so similar to this question but I'm having one of those brain-fart moments and am looking for the Good And Right way to do this.
I am launching a new pthread to handle some data, which means we can only pass a pointer, in this case because we want to pass several things to the thread the pointer is to a struct.
That data struct itself contains a pointer to another data structure.
So, given this setup, what is the correct way to populate & access the nested struct?
struct things_struct
{
int a;
int b;
};
struct thread_params
{
int flag;
struct things_struct *things;
}
int main()
{
struct thread_params params;
struct things_struct the_things;
params.things = &the_things;
// Launch thread
pthread_create(&thrptr, NULL, PrintThings, (void *)params);
//...
}
// The thread
void *PrintThings(void *arg)
{
struct thread_params *params = (thread_params *)arg; // cast back to correct type
int local_a = params->things->a; // is this correct?
//...
}
To add a reference to another similar question (I always find them after posting) there's a similar question here with a similarly simple answer.
Upvotes: 0
Views: 237
Reputation: 81
Yes - your way to access member "a" in things_struct is correct.
But - out of my head - you should pass the address of param to phtread_create(...).
pthread_create(&thrptr, NULL, PrintThings, (void *)¶ms);
Upvotes: 2