gpt4 book ai didi

node.js - Go 有一个 "infinite call stack"等价物吗?

转载 作者:IT王子 更新时间:2023-10-29 00:40:04 25 4
gpt4 key购买 nike

我是 Go 的新手,来自 Node.JS。

在 Node 中,如果我运行这个:

function run(tick = 0) {
if (tick < 1000000) {
return run(tick + 1);
}

return 0;
}

console.log(run());

程序会因为超过最大调用堆栈大小而崩溃。

如果我在 Go 中这样做:

package main

import "fmt"

func run(tick int) (int) {
if (tick < 1000000) {
return run(tick + 1)
}

return 0
}

func main() {
fmt.Println(run(0))
}

这将运行并将 0 打印到标准输出。

我的问题是:

  • 我给出的 Go 示例是否有调用失败的最大调用次数?
  • 这样的代码是 Go 中的反模式吗?

最佳答案

在 Go 中,goroutine 没有固定的堆栈大小。相反,它们从小开始(大约 4KB),并在需要时增长/收缩,看起来给人一种“无限”堆栈的感觉(当然它不可能是真正的无限)。

是的,有一个限制。但是这个限制不是来自调用深度限制,而是堆栈内存限制。此限制由 Go 运行时强制执行,但通常为数百 MB(甚至 GB)。在 Go Playground 上它是 250MB,可以在这个 Go Playground Example 上看到.

在我本地的 Linux 64 位机器上它是 1 GB。

推荐阅读:Dave Cheney: Why is a Goroutine's stack infinite?

回到您的示例:将最大递归调用增加到 1e9 将耗尽堆栈:

if (tick < 1000000000) { ... }

这将导致:

runtime: goroutine stack exceeds 1000000000-byte limit
fatal error: stack overflow

runtime stack:
runtime.throw(0x4b4730, 0xe)
/usr/local/go/src/runtime/panic.go:619 +0x81
runtime.newstack()
/usr/local/go/src/runtime/stack.go:1054 +0x71f
runtime.morestack()
/usr/local/go/src/runtime/asm_amd64.s:480 +0x89

goroutine 1 [running]:
main.run(0xffffde, 0x0)
/home/icza/gows/src/play/play.go:5 +0x62 fp=0xc440088370 sp=0xc440088368 pc=0x483262
main.run(0xffffdd, 0x0)
/home/icza/gows/src/play/play.go:7 +0x36 fp=0xc440088390 sp=0xc440088370 pc=0x483236
main.run(0xffffdc, 0x0)
...

关于node.js - Go 有一个 "infinite call stack"等价物吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49940414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com