我試圖繞過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 回答
- 0 關注
- 219 瀏覽
添加回答
舉報
0/150
提交
取消