c - global variables in pthreads

有些话、适合烂在心里 提交于 2020-01-02 05:19:27

问题


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:


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 .



来源:https://stackoverflow.com/questions/42196179/c-global-variables-in-pthreads

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!