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

标签 c multithreading pthreads posix

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

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

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

这是在 C 中使用 POSIX pthreads。

最佳答案

严格来说,是否允许您从提供线程支持的 C11 角度访问另一个线程的堆栈变量(具有自动存储持续时间的变量)是实现定义的行为,假设堆栈变量仍然存在(例如,您将局部变量的地址从主函数传递给通过 pthread_create 创建的另一个线程,并且主返回通过调用 pthread_exit 退出。因此,传递给线程的变量消失了,它将是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 实现上都应该没问题。

关于c - 线程访问另一个线程的堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49794624/

相关文章:

c - 从结构数组中删除元素

c - __restrict vis-a-vis 流行编译器的函数优化行为

c - 将 "thread number"传递给 pthread_create

c++ - 将多个值打包成一个原子的标准化方法

c++ - 为什么同一内核(超线程)中的两个线程比两个内核的 L1 写访问权限更差?

c - 为什么 printf 在多线程程序中不起作用?

c++ - 完成后关闭线程

C程序链表添加到末尾

c - 如何确定 linux 串行端口上剩余的写入/输出缓冲区空间量?

java - 在删除之前从 ConcurrentHashMap 窃取引用。正确性