求问《GO 语言圣经》里这句话应该怎么解释?
資深大佬 : yuantingwuji 12
下面这段代码来自《 GO 语言圣经》 8.6. 示例: 并发的 Web 爬虫
func main() { worklist := make(chan []string) // lists of URLs, may have duplicates unseenLinks := make(chan string) // de-duplicated URLs // Add command-line arguments to worklist. go func() { worklist <- os.Args[1:] }() // Create 20 crawler goroutines to fetch each unseen link. for i := 0; i < 20; i++ { go func() { for link := range unseenLinks { foundLinks := crawl(link) go func() { worklist <- foundLinks }() //避免死锁 } }() } // The main goroutine de-duplicates worklist items // and sends the unseen ones to the crawlers. seen := make(map[string]bool) for list := range worklist { for _, link := range list { if !seen[link] { seen[link] = true unseenLinks <- link } } } }
书里面说,“crawl 函数爬到的链接在一个专有的 goroutine 中被发送到 worklist 中来避免死锁”,就是上面代码中加了中文注释那一行,为什么不把 worklist <- foundLinks 这个操作加入专有协程就有引起死锁呢?
大佬有話說 (10)