什麼是 Goroutine ?又該如何停止它?

Aliliin發表於2022-02-17

一個 Goroutine 是一個函式或方法執行同時旁邊其他任何夠程採用了特殊的 Goroutine 執行緒。Goroutine 執行緒比標準執行緒更輕量級,大多數 Golang 程式 同時使用數千個 Goroutine。

Goroutine 建立

要建立 Goroutine,請 go 在函式宣告之前新增關鍵字。

go foo(x, y, z)

Goroutine 停止

你可以通過向 Goroutine 傳送一個訊號通道來停止它。Goroutines 只能在被告知檢查時響應訊號,因此您需要在邏輯位置(例如 for 迴圈頂部)包含檢查。

package main
func main() {
    quit := make(chan bool) // chan 訊號
    go func() {
        for {
            select {
            case <-quit:
                return
            default: // ...
            }
        }
    }()
    // ...
    quit <- true
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結
高永立

相關文章