为什么 Go 没有 stackoverflowsGo、stackoverflows

2023-09-07 03:30:24 作者:娇女侧卧坟前坐

我在此演示文稿中读到 http://golang.org/doc/ExpressivenessOfGo.pdf第 42 页:

I read in this presentation http://golang.org/doc/ExpressivenessOfGo.pdf page 42:

安全

- 没有堆栈溢出

这怎么可能?和/或 Go 如何避免这种情况?

How is this possible? and/or how does Go works to avoid this?

推荐答案

这是一个叫做segmented stacks"的特性:每个goroutine都有自己的栈,在堆上分配.

It's a feature called "segmented stacks": every goroutine has its own stack, allocated on the heap.

在最简单的情况下,编程语言实现对每个进程/地址空间使用一个堆栈,通常使用称为 pushpop 的特殊处理器指令(或类似的东西)进行管理) 并实现为从固定地址(通常是虚拟内存的顶部)开始的堆栈帧的动态数组.

In the simplest case, programming language implementations use a single stack per process/address space, commonly managed with special processor instructions called push and pop (or something like that) and implemented as a dynamic array of stack frames starting at a fixed address (commonly, the top of virtual memory).

这是(或曾经)很快,但不是特别安全.当大量代码在同一地址空间(线程)中同时执行时,它会导致麻烦.现在每个人都需要自己的堆栈.但是,所有的堆栈(可能除了一个)都必须是固定大小的,以免它们相互重叠或与堆重叠.

That is (or used to be) fast, but is not particularly safe. It causes trouble when lots of code is executing concurrently in the same address space (threads). Now each needs its own stack. But then, all the stacks (except perhaps one) must be fixed-size, lest they overlap with each other or with the heap.

但是,任何使用堆栈的编程语言也可以通过以不同的方式管理堆栈来实现:使用列表数据结构或类似的结构来保存堆栈帧,但实际上是在堆上分配的.在堆满之前不会出现堆栈溢出.

Any programming language that uses a stack can, however, also be implemented by managing the stack in a different way: by using a list data structure or similar that holds the stack frames, but is actually allocated on the heap. There's no stack overflow until the heap is filled.