0

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)

#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>

pthread_t tid[2];

void* doSomeThing(void *arg)
{
    unsigned long i = 0;
    int MyVariable;
    pthread_t id = pthread_self();
    if(pthread_equal(id,tid[0]))
    {
        printf("\n First thread processing\n");
    }
    else
    {
        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));
        else
            printf("\n Thread created successfully\n");

        i++;
    }
    return 0;
}
ciuz99best
  • 63
  • 1
  • 9
  • the process's memory is shared. – Daniel A. White Dec 29 '19 at 20:48
  • 1
    `MyVariable` is local to the stack of `doSomething` – Daniel A. White Dec 29 '19 at 20:49
  • What @DanielA.White is trying to say is that MyVariable is a function-local variable so regardless of threads or not the value is not shared in any (useable) way. – DisappointedByUnaccountableMod Dec 29 '19 at 21:37
  • These threads don't access any shared variables. Automatic variables, like MyVariable, are not shared across threads. They are all within the memory space of the process, of course, but not shared across threads. The threads *could* share access to a variable if, for example, you passed the address of the same variable from your `main` function into each thread as its starting argument. – jarmod Dec 29 '19 at 22:00

1 Answers1

0

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.

einpoklum
  • 118,144
  • 57
  • 340
  • 684