skinderneath skinderneath - 2 years ago 173
C Question

Passing structures as arguments while using pthread_create()

I tried passing a structure as the 4th argument while using

pthread_create()
with something like this:

pthread_create(&tid1, NULL, calca, &t); //t is the struct


Now whenever I try to access variables in the structure - t.a, t.b or t.c, I keep getting an error - request for member in something not a structure or union.

What alternate method could I use to pass structs into the thread?

Answer Source

You're probably creating the structure in the same scope as pthread_create. This structure will no longer be valid once that scope is exited.

Try creating a pointer to the structure on the heap and pass that structure pointer to your thread. Don't forget to delete that memory somewhere (in the thread if you'll never use it again - or when you no longer need it).

Also, as cyberconte mentioned, if you are going to be accessing that data from different threads, you'll need to lock access to it with a mutex or critical section.

Edit May 14th, 2009 @ 12:19 PM EST: Also, as other people have mentioned, you have to cast your parameter to the correct type.

If you are passing a variable that is a global structure (which you seem to be insisting upon), your thread function will have to cast to the type:

void my_thread_func(void* arg){
    my_struct foo = *((my_struct*)(arg)); /* Cast the void* to our struct type */
    /* Access foo.a, foo.b, foo.c, etc. here */
}

Or, if you are passing a pointer to your structure:

void my_thread_func(void* arg){
    my_struct* foo = (my_struct*)arg; /* Cast the void* to our struct type */
    /* Access foo->a, foo->b, foo->c, etc. here */
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download