Golang关闭读者频道

时间:2019-06-26 09:20:59

标签: go

this文章中,有关使用通道和goroutine实现Worker池。我可以将其用作自己的工作池实现的基础,该工作池实现对远程服务的http调用。

该代码正确关闭了work通道,但未提及如何关闭result通道。即使我自己考虑了一下,也不容易看出在什么时候关闭result chan。并且像文章中那样保持打开状态,即使所有main完成处理工作后,workers也不会返回。

这是代码的相关部分。

func main() {

// In order to use our pool of workers we need to send
// them work and collect their results. We make 2
// channels for this.
jobs := make(chan int, 100)
results := make(chan int, 100)

// This starts up 3 workers, initially blocked
// because there are no jobs yet.
for w := 1; w <= 3; w++ {
    go worker(w, jobs, results)
 }

// Here we send 5 `jobs` and then `close` that
// channel to indicate that's all the work we have.
for j := 1; j <= 5; j++ {
    jobs <- j
 }
close(jobs)

// Finally we collect all the results of the work.
// This also ensures that the worker goroutines have
// finished. An alternative way to wait for multiple
// goroutines is to use a [WaitGroup](waitgroups).
for result := range results {
    fmt.Println(result)
  }
}

如何正确关闭result通道?

playground

0 个答案:

没有答案