Suppose I defined a function in file function.c, and in main.c I create multiple pthreads to execute the function in function.c.
If in function.c, I define a global variable, for example, int foo;
Then, my question is, does every thread has its own instance of this variable "foo" or do they share a single "foo"?
Global var is a var. Whose scope is within the entire *.c file.. they can be accesible wherever they use in same file...
Threads are lieghtweight process but in multithreaded process (or a multithreaded file) all threads work together to provide diffrent-2 functionality for related process.. So, because they're not stand-alone process so they access global variable in a global manner...
Local variables defined in pthreads are locally accesible in the thread in which they are declared.
Any thread does'nt know about local variable of another thread .
They share a single
foo
variable. Global variable always exists only once per process and is usually protected by mutex to avoid concurrent access.Since C11 you can use thread_local to declare the variable as local per thread: