首頁  >  文章  >  後端開發  >  為什麼 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.
  • 說明

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