首頁  >  文章  >  後端開發  >  為什麼在本機上運行相同的程式碼時 Go Playground 會逾時?

為什麼在本機上運行相同的程式碼時 Go Playground 會逾時?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-23 23:25:29434瀏覽

Why Does the Go Playground Timeout While Running the Same Code on a Local Machine?

Go Playground 和Go on Your Machine 之間的差異:Goroutine 執行

為了解決有關Goroutine 執行的混亂,在兩者上都執行了程式碼片段Go Playground 和本機。 Playground 產生錯誤“進程花費太長時間”,建議創建一個永久運行的 Goroutine,而本地機器幾乎產生即時輸出。這就提出了一個問題:當主 Goroutine 完成時,other() 函數中的 Goroutine 是否退出,還是繼續在背景運行。

說明

On the Go Playground ,GOMAXPROCS 設定為 1。這表示一次只執行一個 Goroutine。如果沒有阻塞,調度程序將不會切換到其他 Goroutine。

在程式碼中,主 Goroutine 在 did 通道上啟動並阻塞。調度程式必須切換到 other() Goroutine,該 Goroutine 在完成通道上發送一個值,使兩個 Goroutine 都可以運行。調度程序選擇繼續執行other()。由於 GOMAXPROCS 為 1,主 Goroutine 仍處於阻塞狀態。

other() 然後啟動無限循環 Goroutine。該 Goroutine 繼續運行,導致主 Goroutine 無法恢復。因此,Playground 會發生逾時。

在本地,GOMAXPROCS 通常會超過 1。因此,當無限循環 Goroutine 運行時,另一個 Goroutine(可能是主 Goroutine)會同時執行。當主 Goroutine 返回時,程式終止,因為它不會等待其他非主 Goroutine 的完成。

Go Playground 修改

透過明確設定 GOMAXPROCS 為1 在 Go Playground 上,可以重現「進程花費太長時間」的行為。相反,將 GOMAXPROCS 設定為較高的值,例如 2,通常會導致不同的執行順序並成功終止而不會逾時。

以上是為什麼在本機上運行相同的程式碼時 Go Playground 會逾時?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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