内存中的静态和全局变量

2022-01-12 00:00:00 multithreading multiprocessing c c++
  1. 栈中存储的静态变量是否类似于全局变量?如果是这样,它们如何受到保护以仅允许本地类访问?

  1. Are static variables stored on the stack itself similar to globals? If so, how are they protected to allow for only local class access?

在多线程上下文中,是否担心这块内存可以被其他线程/内核直接访问?或者为什么我们不能在多进程/线程环境中使用静态/全局?

In a multi threaded context, is the fear that this memory can be directly accessed by other threads/ kernel? or why cant we use static/global in multi process/ thread enviornment?

推荐答案

存储在堆栈中的变量本质上是临时的.它们属于一个函数等,当函数返回并且相应的堆栈帧被弹出时,堆栈变量随之消失.由于全局变量被设计为在任何地方都可以访问,因此它们不能脱离上下文,因此存储在堆上(或二进制的特殊数据部分)而不是堆栈上.static 变量也是如此;因为它们必须在函数调用之间保持它们的值,所以当函数返回时它们不会消失,因此它们不能被分配到堆栈上.

Variables stored on the stack are temporal in nature. They belong to a function, etc and when the function returns and the corresponding stack frame is popped off, the stack variables disappear with it. Since globals are designed to be accessible everywhere, they must not go out of context and thus are stored on the heap (or in a special data section of the binary) instead of on the stack. The same goes for static variables; since they must hold their value between invocations of a function, they cannot disappear when the function returns thus they cannot be allocated on the stack.

static 变量的保护而言,IIRC 这主要由编译器完成.即使变量在堆上,您的编译器也知道该变量在其中有效的有限上下文,并且从该上下文之外访问 static 的任何尝试都将导致未知标识符"或类似错误.错误访问堆变量的唯一另一种方法是,如果您知道 static 的地址并且盲目地取消引用指向它的指针.这应该会导致运行时内存访问错误.

As far as protection of static variables goes, IIRC this is mainly done by the compiler. Even though the variable is on the heap, your compiler knows the limited context in which that variable is valid and any attempt to access the static from outside that context will result in an "unknown identifier" or similar error. The only other way to access the heap variable incorrectly is if you know the address of the static and you blindly de-reference a pointer to it. This should result in a run-time memory access error.

在多线程环境中,仍然可以使用全局变量和静态变量.但是,您必须更加小心.您必须保证一次只有一个线程可以访问该变量(通常通过某种锁定机制,例如互斥锁).对于函数内部的 static 局部变量,您必须确保如果从多个线程按顺序调用函数(即从线程 1 调用,然后从线程 2 调用),您的函数仍将按预期运行,然后是线程 1,然后是线程 2,等等).这通常更难做到,并且许多依赖 static 成员变量的函数因此不是线程安全的(strtok 是一个值得注意的例子).

In a multi-threaded environment, it is still okay to use globals and static variables. However, you have to be a lot more careful. You must guarantee that only one thread can access the variable at a time (typically through some kind of locking mechanism such as a mutex). In the case of static local variables inside a function, you must ensure that your function will still function as expected if it is called from multiple threads sequentially (that is, called from thread 1, then from thread 2, then thread 1, then thread 2, etc etc). This is generally harder to do and many functions that rely on static member variables are not thread-safe because of this (strtok is a notable example).

相关文章