c - global variables in pthreads

2019-05-04 20:21发布

问题:

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"?

回答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;


回答2:

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 .



标签: c scope pthreads