尽管sync.waitGroup (wg) 是前进的规范方法,但它确实需要您在wg.Wait 之前至少完成一些wg.Add 调用才能完成。这对于像网络爬虫这样的简单事物可能不可行,因为您事先不知道递归调用的数量,并且需要一段时间来检索驱动 wg.Add 调用的数据。毕竟,在知道第一批子页面的大小之前,你需要加载和解析第一页。
我使用渠道编写了一个解决方案,避免在我的解决方案中使用 waitGroup Tour of Go - web crawler 练习。每次启动一个或多个 go-routines 时,您都会将号码发送到 children 频道。每次 goroutine 即将完成时,您都会向 done 频道发送 1。当孩子的总和等于完成的总和时,我们就完成了。
我唯一关心的是results 频道的硬编码大小,但这是(当前)Go 限制。
// recursionController is a data structure with three channels to control our Crawl recursion.
// Tried to use sync.waitGroup in a previous version, but I was unhappy with the mandatory sleep.
// The idea is to have three channels, counting the outstanding calls (children), completed calls
// (done) and results (results). Once outstanding calls == completed calls we are done (if you are
// sufficiently careful to signal any new children before closing your current one, as you may be the last one).
//
type recursionController struct {
results chan string
children chan int
done chan int
}
// instead of instantiating one instance, as we did above, use a more idiomatic Go solution
func NewRecursionController() recursionController {
// we buffer results to 1000, so we cannot crawl more pages than that.
return recursionController{make(chan string, 1000), make(chan int), make(chan int)}
}
// recursionController.Add: convenience function to add children to controller (similar to waitGroup)
func (rc recursionController) Add(children int) {
rc.children <- children
}
// recursionController.Done: convenience function to remove a child from controller (similar to waitGroup)
func (rc recursionController) Done() {
rc.done <- 1
}
// recursionController.Wait will wait until all children are done
func (rc recursionController) Wait() {
fmt.Println("Controller waiting...")
var children, done int
for {
select {
case childrenDelta := <-rc.children:
children += childrenDelta
// fmt.Printf("children found %v total %v\n", childrenDelta, children)
case <-rc.done:
done += 1
// fmt.Println("done found", done)
default:
if done > 0 && children == done {
fmt.Printf("Controller exiting, done = %v, children = %v\n", done, children)
close(rc.results)
return
}
}
}
}
Full source code for the solution