Passing structures as arguments while using pthread_create()
Solution 1
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 */
}
Solution 2
If you're inside your thread function, the argument you pass is a void*. You'll need to cast it to a struct before you can use it as such.
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 */
}
Solution 3
Create a semaphore
Create another structure that consists of a pointer to your structure and the semaphore handle
Pass a pointer to this new structure to pthread_create
In the parent thread, i.e. that called pthread_create, wait on the semaphore
In the child thread, copy members of your structure to local variables or save them elsewhere
In the child thread, signal the semaphore
In the parent thread, close the semaphore
skinderneath
Updated on July 09, 2022Comments
-
skinderneath almost 2 years
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?