0

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.

2
  • Yes. <!-- do html comments show? --> Commented Apr 9, 2014 at 12:22
  • @RedX - Yes they do. Were you actually answering my question or just testing your theory about comments? Commented Apr 9, 2014 at 12:30

1 Answer 1

2

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 *)&params);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - I didn't write the rest very thoroughly as it was only for illustration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.