c - global variables in pthreads
Solution 1
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:
#include <threads.h>
...
thread_local int perThreadInt;
Solution 2
A global varariable is a variable whose scope is within the entire *.c file. They can be accessible wherever they use in same file.
Threads are lightweight process but in multi-threaded process (or a multi-threaded file) all threads work together to provide different-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 accessible in the thread in which they are declared.
Any thread doesn't know about local variable of another thread .
zanyman
Updated on June 04, 2022Comments
-
zanyman almost 2 years
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"?