我试图绕过goroutines。我创建了一个简单的程序,可以在多个搜索引擎中并行执行相同的搜索。此刻,为了跟踪回复的数量,我计算了收到的数量。虽然看起来有点业余。在下面的代码中,是否有更好的方法知道何时收到所有goroutine的响应?package mainimport ( "fmt" "net/http" "log")type Query struct { url string status string}func search (url string, out chan Query) { fmt.Printf("Fetching URL %s\n", url) resp, err := http.Get(url) if err != nil { log.Fatal(err) } defer resp.Body.Close() out <- Query{url, resp.Status}}func main() { searchTerm := "carrot" fmt.Println("Hello world! Searching for ", searchTerm) searchEngines := []string{ "http://www.bing.co.uk/?q=", "http://www.google.co.uk/?q=", "http://www.yahoo.co.uk/?q="} out := make(chan Query) for i := 0; i < len(searchEngines); i++ { go search(searchEngines[i] + searchTerm, out) } progress := 0 for { // is there a better way of doing this step? if progress >= len(searchEngines) { break } fmt.Println("Polling...") query := <-out fmt.Printf("Status from %s was %s\n", query.url, query.status) progress++ }}
1 回答
- 1 回答
- 0 关注
- 203 浏览
添加回答
举报
0/150
提交
取消