Memory sharing between threads in C


can someone please explain exactly what memory is being shared between threads? I got the code from a website just so I can explain what I don't understand exactly. I want to know, if all the threads after they're created they will execute the function doSomeThing and will they share the same value for MyVariable or every thread will have separate values for it. (ignore the fact that there isn't any value assigned to the variable)


pthread_t tid[2];

void* doSomeThing(void *arg)
    unsigned long i = 0;
    int MyVariable;
    pthread_t id = pthread_self();
        printf("\n First thread processing\n");
        printf("\n Second thread processing\n");
    for(i=0; i<(0xFFFFFFFF);i++);
    return NULL;
int main(void)
    int i = 0;
    int err;
    while(i < 2)
        err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
        if (err != 0)
            printf("\ncan't create thread :[%s]", strerror(err));
            printf("\n Thread created successfully\n");

    return 0;
asked on Stack Overflow Dec 29, 2019 by ciuz99best

1 Answer


You've actually asked two separate questions.

what memory is being shared between threads?

Well, all memory (on typical OSes). A main difference between threads and processes is that different processes have different memory spaces, which threads within a process have the same memory space.

See also:

What is the difference between a process and a thread?

will [the two threads] share the same value for MyVariable?

No! and that's because each thread has its own stack (and their own registers state). Now, the stacks are both in the shared memory space, but each thread uses a different one.

So: Sharing memory space is not the same as sharing the value of each variable.

answered on Stack Overflow Dec 29, 2019 by einpoklum • edited Dec 29, 2019 by einpoklum

User contributions licensed under CC BY-SA 3.0