线程访问另一个线程的堆栈 [英] Thread access to stack of another thread

查看:544
本文介绍了线程访问另一个线程的堆栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Am I right in thinking it is OK for a thread to access a variable that exists in the stack of another thread?

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

This is assuming the function in which the stack variable was instantiated has not yet returned.

我想我读到某个地方线程应该只共享堆内存,但是我现在在问那是否正确?

I think I read somewhere that threads should only share heap memory but I'm now questioning whether that is correct?

这是在C语言中使用POSIX pthreads.

This is using POSIX pthreads in C.

推荐答案

严格来说,是否允许从C11角度访问另一个线程的堆栈变量(具有自动存储持续时间的变量)是实现定义的行为,提供线程支持(但接口与POSIX线程不同),假设堆栈变量仍然有效(例如,您将本地变量的地址从主函数传递给通过

Strictly speaking, it's an implementation-defined behaviour whether you are allowed to access the stack variable (variable with automatic storage duration) of another thread from a C11 perspective which provides thread support (but the interfaces are different to POSIX threads), assuming that stack variable is still alive (e.g., you pass an address of a local variable from main function to another thread created via 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. This is no different to using pointer to local variables from other function after that function has returned - threads or not).

但是在实践中,这很可能适用于大多数(全部?)POSIX线程实现.我不知道任何不支持此功能的POSIX实现.

But in practice, this is likely to work on most (all?) POSIX thread implementations. I am not aware of any POSIX implementation where this isn't supported.

查看 POSIX标准,它实际上要求支持访问自动变量:

Looking at the POSIX standard, it actually requires that access to automatic variables be supported:

一个流程中的单个控制流.每个线程都有自己的线程ID,调度优先级和策略,errno值,浮点环境,特定于线程的键/值绑定以及支持控制流所需的系统资源.所有人都可以访问其地址可以由线程确定的任何事物,包括但不限于静态变量,通过malloc()获得的存储,通过实现定义的函数获得的可直接寻址的存储以及自动变量同一进程中的线程.

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实现中都应该可以.

So this should be fine on any POSIX implementation.

这篇关于线程访问另一个线程的堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆