Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can pthreads only share global resources?

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.

like image 364
ldog Avatar asked Dec 18 '22 06:12

ldog


1 Answers

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!
}
like image 153
brool Avatar answered Jan 30 '23 06:01

brool