I'm trying to share a structure between two threads that is not a global variable. The variable itself is instantiated on the stack in the main function, then its pointer is passed as the parameter to both threads on the start up of both threads.
What I'm finding is that when I change the value of a member of that structure that change is not reflected ever in the other pthread. Is there a way to share a non-global variable (say an integer for example) between two threads, such that changes done to that variable in one thread appear in the other?
This is all because I want to avoid adding global variables for code-maintainability.
Remember that threads get their own stack -- so if you pass an integer in and the function goes out of scope, you're referring to memory that now holds something entirely different.
void foo(void)
{
pthread_t t1, t2;
struct foo common_value;
if (pthread_create(&t1, NULL, a, &common_value) != 0)
{
return -1;
}
if (pthread_create(&t2, NULL, b, &common_value) != 0)
{
return -1;
}
// upon exiting this function, common_value is no longer what you think it is!
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With