AdSense

網頁

2022/12/7

Golang 使用Channel取得goroutine的錯誤 to get goroutine error by channel

Go的goroutine函式因為是另個thread所以無法將錯誤以return回傳到main goroutine,因此可利用Channel來將錯誤(或其他結果)回傳到main goroutine。


範例

下面程式中建立一個型別為error的channel變數forever。在另一個goroutine中當錯誤發生時以forever <- error將錯誤發送至forever,然後在main goroutine以<-forever接收並印出。

main.go

package main

import (
    "fmt"
)

func main() {
    limit := 3
    forever := make(chan error)

    go func() {
        count := 0
        for {
            if count <= limit {
                fmt.Printf("count=%d\n", count)
                count++
            } else {
                forever <- fmt.Errorf("count exceed limit=%d", limit)
            }
        }
    }()

    err := <-forever
    close(forever)
    fmt.Println(err)
}

測試

程式執行印出以下結果。

count=0
count=1
count=2
count=3
count exceed limit=3


沒有留言:

AdSense