尝试使用go例程时无法刮取数据
我试图从给定的单词开始,用BFS搜索给定单词的相关单词,并在dictionary.com上搜索每个相关单词 我在没有并发性的情况下尝试了这段代码,它工作得很好,但是需要花费很多时间,因此,我尝试使用go例程,但是我的代码在第一次迭代后就卡住了。BFS的第一级工作正常,但在第二级它挂起尝试使用go例程时无法刮取数据,go,goroutine,Go,Goroutine,我试图从给定的单词开始,用BFS搜索给定单词的相关单词,并在dictionary.com上搜索每个相关单词 我在没有并发性的情况下尝试了这段代码,它工作得很好,但是需要花费很多时间,因此,我尝试使用go例程,但是我的代码在第一次迭代后就卡住了。BFS的第一级工作正常,但在第二级它挂起 package main import ( "fmt" "github.com/gocolly/colly" "sync" ) var wg sync.WaitGroup func
package main
import (
"fmt"
"github.com/gocolly/colly"
"sync"
)
var wg sync.WaitGroup
func buildURL(word string) string {
return "https://www.dictionary.com/browse/" + string(word)
}
func get(url string) []string {
c := colly.NewCollector()
c.IgnoreRobotsTxt = true
var ret []string
c.OnHTML("a.css-cilpq1.e15p0a5t2", func(e *colly.HTMLElement) {
ret = append(ret, string(e.Text))
})
c.Visit(url)
c.Wait()
return ret
}
func threading(c chan []string, word string) {
defer wg.Done()
var words []string
for _, w := range get(buildURL(word)) {
words = append(words, w)
}
c <- words
}
func main() {
fmt.Println("START")
word := "jump"
maxDepth := 2
//bfs
var q map[string]int
nq := map[string]int {
word: 0,
}
vis := make(map[string]bool)
queue := make(chan []string, 5000)
for i := 1; i <= maxDepth; i++ {
fmt.Println(i)
q, nq = nq, make(map[string]int)
for word := range q {
if _, ok := vis[word]; !ok {
wg.Add(1)
vis[word] = true
go threading(queue, word)
for v := range queue {
fmt.Println(v)
for _, w := range v {
nq[w] = i
}
}
}
}
}
wg.Wait()
close(queue)
fmt.Println("END")
}
永远挂在这里,计数器=2未打印
您可以在此查看相关词语。根据
仅当缓冲区已满时才发送到缓冲通道块。
当缓冲区为空时接收块
因此,在本例中,您将使用5000作为长度创建一个缓冲通道
i:=1的
;ifor v:=范围队列{
这是永久阻止的对象。范围队列
仅在队列
关闭时才会返回。并且它仅在应用程序代码末尾附近关闭。
START
1
[plunge dive rise upsurge bounce hurdle fall vault drop advance upturn inflation increment spurt boost plummet skip bound surge take]
vis := make(map[string]bool)
queue := make(chan []string, 5000)
for i := 1; i <= maxDepth; i++ {
fmt.Println(i)
q, nq = nq, make(map[string]int)
unvisited := 0
for word := range q {
if _, ok := vis[word]; !ok {
vis[word] = true
unvisited++
wg.Add(1)
go threading(queue, word)
}
}
wg.Wait() // wait until jobs are done
for j := 0; j < unvisited; j++ { // << does not block as we know how much
v := <-queue // we exactly try to get unvisited amount
fmt.Println(v)
for _, w := range v {
nq[w] = i
}
}
}