// _Closing_ a channel indicates that no more values
// will be sent on it. This can be useful to communicate
// completion to the channel's receivers.
package main
import "fmt"
// In this example we'll use a `jobs` channel to
// communicate work to be done from the `main()` goroutine
// to a worker goroutine. When we have no more jobs for
// the worker we'll `close` the `jobs` channel.
func main() {
jobs := make(chan int, 5)
done := make(chan bool)
// Here's the worker goroutine. It repeatedly receives
// from `jobs` with `j, more := <-jobs`. In this
// special 2-value form of receive, the `more` value
// will be `false` if `jobs` has been `close`d and all
// values in the channel have already been received.
// We use this to notify on `done` when we've worked
// all our jobs.
for i := 1; i <= 3; i++ {
go func() {
for {
j, more := <-jobs
if more {
fmt.Println("received job", j)
} else {
fmt.Println("received all jobs")
done <- true
return
}
}
}()
}
// This sends 3 jobs to the worker over the `jobs`
// channel, then closes it.
j := 0
for {
j++
jobs <- j
fmt.Println("sent job", j)
}
close(jobs)
fmt.Println("sent all jobs")
// We await the worker using the
// [synchronization](channel-synchronization) approach
// we saw earlier.
<-done
}
https://play.golang.org/p/x28R_g8ftS
我正在尝试做的是从分页 url 端点获取所有响应。 jobs 是一个存储页码的 channel 。我有一个函数 if more{} 检查空响应,我有
done <- true
return
我认为这会关闭 go 例程。
但是,页面生成器 for{j++; jobs <- j}
导致它陷入循环。知道如何解决这个问题吗?
最佳答案
根据定义,没有条件的 for 循环是无限循环。除非你加入一些逻辑来打破这个无限循环,否则你永远无法摆脱它。
在您的 playground 中,您的评论暗示您要发送 3 个作业。您应该相应地更改 for 循环:
for j := 0; j < 3; j++ {
jobs <- j
fmt.Println("sent job", j)
}
关于GO程序陷入循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46187181/