sync.WaitGroup
可用于在此等待所有goroutine,然后关闭
quotes
频道:
func getPrice(quotes chan<- string, onExit func()) {
go func() {
defer onExit()
req, _ := http.NewRequest("GET", "https://some/api", nil)
req.Header.Set("Accept", "application/json")
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
panic(err) // should be handled properly
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
quotes <- string(body)
}()
}
func main() {
const max = 3
var wg sync.WaitGroup
quotes := make(chan string, max)
for i := 0; i < max; i++ {
wg.Add(1)
getPrice(quotes, func() { wg.Done() })
}
go func() {
defer close(quotes)
wg.Wait()
}()
for n := range quotes {
fmt.Printf("\n%s", n)
}
}