首页  >  文章  >  后端开发  >  为什么 Go Goroutine 的行为在 Playground 和本地执行之间有所不同?

为什么 Go Goroutine 的行为在 Playground 和本地执行之间有所不同?

DDD
DDD原创
2024-10-23 14:35:33374浏览

Why Do Go Goroutine Behaviors Differ Between the Playground and Local Execution?

Go Playground 和本地机器执行之间的不一致行为

背景

为了澄清有关 goroutine 的误解,一位用户转向了 Go Playground并执行以下代码:

<code class="go">package main

import (
    "fmt"
)

func other(done chan bool) {
    done <- true
    go func() {
        for {
            fmt.Println("Here")
        }
    }()
}

func main() {
    fmt.Println("Hello, playground")
    done := make(chan bool)
    go other(done)
    <-done
    fmt.Println("Finished.")
}</code>

观察到的结果

Go Playground:

  • 遇到错误:“处理时间太长."
  • 暗示其他 goroutine 永久运行。

本地执行:

  • 产生的输出几乎立即:

    Hello, playground.
    Finished.
  • 表示 other 内的 goroutine 在主 goroutine 完成后终止。

说明

Go Playground:

  • 默认 GOMAXPROCS 设置为 1。
  • 一次只有一个 goroutine 执行,防止 goroutine 非阻塞时调度程序切换。
  • main goroutine 阻塞等待来自 done 通道的消息。
  • 其他 goroutine 无限期执行,导致超时。

本地执行:

  • GOMAXPROCS 可能设置为 CPU 核心数,通常默认为大于 1 的值。
  • 调度程序在 goroutine 之间切换,允许主 goroutine 即使在非-阻塞并发运行的 goroutine。
  • 一旦 main() 退出,程序将终止,而不等待无限期运行的 goroutine 完成。

非确定性行为

请注意,Go Playground 目前使用输出的缓存版本,因此后续运行可能无法准确反映实际执行情况。

结论

了解 GOMAXPROCS 对 goroutine 执行的影响对于设计至关重要适当的并发模型。 Go Playground 上的默认设置可能并不总是模仿本地机器的行为,这凸显了在不同配置下进行测试的重要性。

以上是为什么 Go Goroutine 的行为在 Playground 和本地执行之间有所不同?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn