线程访问另一个线程的堆栈

Thread access to stack of another thread

我认为一个线程可以访问另一个线程的堆栈中存在的变量是正确的吗?

这是假设实例化堆栈变量的函数尚未返回。

我想我在某处读到线程应该只共享堆内存,但我现在质疑这是否正确?

这是在 C 中使用 POSIX pthreads。

严格来说,从提供线程支持的C11角度来看,是否允许您访问另一个线程的堆栈变量(具有自动存储持续时间的变量)是一个实现定义的行为(但接口不同于POSIX 线程),假设堆栈变量仍然存在(例如,您将局部变量的地址从 main 函数传递到通过 pthread_create and the main returns exits by calling pthread_exit.Thus the variable passed to the thread is gone and it would be undefined behaviour 创建的另一个线程)。这与使用指向来自其他线程的局部变量的指针没有什么不同该函数返回后的函数 - 线程与否)。

但实际上,这可能适用于大多数(所有?)POSIX 线程实现。我不知道有任何 POSIX 实现不受支持。


POSIX standard,其实是要求支持访问自动变量:

A single flow of control within a process. Each thread has its own thread ID, scheduling priority and policy, errno value, floating point environment, thread-specific key/value bindings, and the required system resources to support a flow of control. Anything whose address may be determined by a thread, including but not limited to static variables, storage obtained via malloc(), directly addressable storage obtained through implementation-defined functions, and automatic variables, are accessible to all threads in the same process.

(强调我的)。

所以这在任何 POSIX 实现上都应该没问题。