尽管(wg) 是规范的前进方式,但它确实需要您在完成所有调用之前sync.waitGroup
至少执行一些调用。这对于像网络爬虫这样的简单事物可能不可行,因为您事先不知道递归调用的数量,并且需要一段时间来检索驱动调用的数据。毕竟,在知道第一批子页面的大小之前,你需要加载和解析第一页。wg.Add
wg.Wait
wg.Add
我使用通道编写了一个解决方案,waitGroup
在我的解决方案中避免了Tour of Go - 网络爬虫练习。每次启动一个或多个 go-routines 时,您都会将数字发送到children
频道。每次 goroutine 即将完成时,您都会向频道发送1
一个done
。当孩子的总和等于完成的总和时,我们就完成了。
我唯一关心的是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
}
}
}
}
解决方案的完整源代码