今天,我了解了.我所理解的问题是,我正在使用 WaitGroup 的函数来执行所有戈鲁廷。buffered channelsWait但并非所有的戈鲁廷都在执行,程序在没有等待所有戈鲁廷完成的情况下结束。法典:func main() { // initializing a WaitGroup var wg sync.WaitGroup // adding 3 counts/buffer to the WaitGroup wg.Add(3) fmt.Println("Start Goroutines") go responseSize("https://www.golangprograms.com", &wg) go responseSize("https://stackoverflow.com", &wg) go responseSize("https://coderwall.com", &wg) // wait for goroutines to finish wg.Wait() fmt.Println("Terminating the main program")}// just prints the response size of the body returned func responseSize(url string, wg *sync.WaitGroup) { // schedule the Done() call when the goroutine is finished wg.Done() fmt.Println("Step1: ", url) response, err := http.Get(url) if err != nil { log.Fatal(err) } fmt.Println("Step2: ", url) body, err := ioutil.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Println("Step3: ", len(body))}我在这里错过了什么吗?
1 回答

偶然的你
TA贡献1841条经验 获得超3个赞
而不是
wg.Done()
用
defer wg.Done()
按照它的写作方式,你的戈鲁丁信号表明,当它们开始运行时,工作已经消失,而不是当它们结束时,允许主戈鲁廷继续和退出。
- 1 回答
- 0 关注
- 109 浏览
添加回答
举报
0/150
提交
取消