写入错误通道会停止执行

我正在尝试sync.WorkGroup使用通道启动多个 go-routines,并从这些工作人员那里收集错误。(这是一个好方法吗?)。每当我尝试写入错误通道时,程序似乎都会停止。无法弄清楚它的原因。


场景看起来像这样 -


package main


import (

    "fmt"

    "time"

)


func worker(id int, i int, errs chan<- errs) {

   defer wg.Done()

   errs <- fmt.Errorf("Sample Error") // This is where the executions seems to be stuck

   return 

}


func main() {

    errs := make(chan int)

    var wg sync.WaitGroup

 

    for w := 1; w <= 3; w++ {

        wg.Add(1)

        go worker(w, w, errs)

    }

    wg.Wait()

    fmt.Printf("Hello, all tasks done.") // Never executed.

    close(errs)

    for err := range errs{

         fmt.Printf("%s", err.Error())

   }


}


蝴蝶刀刀
浏览 133回答 1
1回答

慕标琳琳

如果没有其他 goroutine 从它读取,则通道写入将阻塞。当您写入错误通道时,没有其他 goroutine 从它读取,因此它会阻塞。你的程序有几个问题:您必须在调用之前从错误通道开始读取wg.Wait,因为这将等待 goroutine 完成,但如果您不从错误通道读取,goroutine 将不会运行。关闭错误通道后,您正尝试从错误通道中读取。像这样的东西应该工作:errs := make(chan int, numJobs)go func() {&nbsp; &nbsp; for err := range errs{&nbsp; &nbsp; &nbsp; &nbsp;fmt.Printf("%s", err.Error())&nbsp;}()for w := 1; w <= 3; w++ {&nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; go worker(w, w, results)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go