首頁  >  文章  >  後端開發  >  Go Playground 和本機之間 Goroutine 的行為有何不同?

Go Playground 和本機之間 Goroutine 的行為有何不同?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-23 17:42:24452瀏覽

How Do Goroutines Behave Differently Between Go Playground and Local Machine?

Go Playground 和本地機器上的Go 之間的差異

問題:Go Playground 中的Goroutines 與本地機器

為了澄清對Goroutines的誤解,此程式碼在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 中創建的Goroutine 無限期地運行。

但是,在本地運行相同的程式碼會產生立即輸出:

<code class="go">Hello, playground.
Finished.</code>

這表示當主Goroutine 時,其他Goroutine 退出

說明

差異是由於GOMAXPROCS 的預設值造成的。

在 Go Playground 上, GOMAXPROCS 設定為 1。意味著一次只能運行一個 goroutine。當 other 中建立的 Goroutine 不阻塞時(例如,透過在通道上等待),調度程式將不會切換到其他 Goroutine。

由於主 Goroutine 在 did 通道上阻塞,因此調度程式會切換到其他內部的 goroutine。然後,other 中的 goroutine 啟動另一個 goroutine,並無限循環。由於 GOMAXPROCS 為 1,主 Goroutine 不再繼續,死循環繼續運行,導致逾時。

在本機上, GOMAXPROCS 一般預設為 CPU 核數(例如,4 或 8)。這允許多個 goroutine 並發運行。當主 Goroutine 在完成通道上阻塞時,排程器會切換到另一個 Goroutine。這可能是其他 Goroutine 中的 Goroutine,也可能是運行無限循環的 Goroutine。

由於主 Goroutine 最終會完成,因此無限循環將不再運行。因此,程式將正常終止,而無需等待無限循環完成。

結論

在 Go Playground 中執行 goroutine 時,考慮 GOMAXPROCS 的預設值非常重要。若要模擬多goroutine並發,請明確將GOMAXPROCS設定為較高的值,例如runtime.GOMAXPROCS(2)。在本機執行中,GOMAXPROCS 的預設設定通常允許預期的並發行為。

以上是Go Playground 和本機之間 Goroutine 的行為有何不同?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn