I read that threads share the memory address space of it’s parent thread.
If that is true , why can’t a thread function access a local variable belonging to it’s parent thread ?
void* PrintVar(void* arg){
printf( "%d\n", a);
}
int main(int argc, char*argv[]) {
int a;
a = 10;
pthread_t thr;
pthread_create( &thr, NULL, PrintVar, NULL );
}
If the thread shares the address space , then the function PrintVar should have been able to print the value of variable a , right ?
I read this piece of info on http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html
Threads in the same process share:
Process instructions
Most data
open files (descriptors)
signals and signal handlers
current working directory
User and group id
If that is true, then why does int a not qualify as a shared variable ?
I’d like to see an example code where the file descriptors are shared
you couldn’t do that even if this were not a thread, because a is out of scope.
put a in the global scope, like so:
This is actually not an issue of threads. consider the following code:
This obviously won’t work, because the variable name
adeclared inmainis not visible inPrintVar, because it’s in the local scope of another block. This is a compile-time problem, the compiler just doesn’t know what you mean byawhen you mention it inPrintVar.But there is also another threading issue. when the main thread of a process exit, all other threads are terminated (specifically, when any thread calls
_exit, then all threads are terminated, and_startcalls_exitaftermainreturns). but your main returns immediately after invoking the other thread. To prevent this, you should callpthread_joinwhich will wait for a thread to exit before returning. that’ll look like this