linux 如何管理线程堆栈

How does linux manage threads stack

在英特尔 x86 32/64 位架构上,每个线程都拥有自己的堆栈。 在同一进程的线程之间进行内核切换的地方,当前线程的堆栈和寄存器在某处备份。我想它在堆栈中?

这是否意味着如果我的进程中有 N 个线程,我的进程内存中将有 N+1 个堆栈?还是由内核管理?如果知道另一个线程的esp/bsp,我可以线程读取另一个线程的堆栈吗? (我说的是同一进程的线程)

Where the kernel switch between threads of the same process, stack and registers of current threads are backuped somewhere. I suppose it is in a stack ?

是的,没错。通常,重新安排是由 timer interrupt 触发的。 timer interrupt,与任何其他硬件中断[1] 一样,请求 CPU 停止处理当前正在处理的内容并执行一些特殊代码,即 interrupt service routine。内核可以自己设置这个,所以它只是内核提供的一个函数。通常,内核在中断发生时做的第一件事是将所有寄存器压入堆栈。内核唯一需要保存的是栈顶,esp。当内核现在切换到另一个线程时,它所要做的就是加载新线程 esp 并弹出所有寄存器。

Does that mean if i have N thread on my process, i will have N+1 stacks in the process memory ?

您很可能在内存中有 N 个堆栈,在内核内存中有 N 个堆栈,作为中断,调用内核代码,加载另一个堆栈。通常,每个线程都有自己的内核堆栈,但请不要引用我的话。

Can i thread read the stack of another thread if it knows esp/bsp of that thread ? (i am talking about threads of the same process)

是的,你可以。同一进程中的线程共享相同的虚拟地址 space,因此如果您知道线程堆栈的确切位置,您就可以访问该内存。


[1]: 硬件中断由Programmable Interrupt Controller from the "outside" of the CPU when something happens, like a key-press on your keyboard. There are also software interrupts, which are triggered by the cpu/the software itself, either intended or to handle an error (division by zero). Software interrupts are one way to implement systemcalls, because you can not call ring-0 code from ring-3 code. A interrupt however can jump "up" to ring-0 if the TSS触发。