围棋戈鲁丁没有运行

今天,我了解了.我所理解的问题是,我正在使用 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))

}

我在这里错过了什么吗?


慕尼黑5688855
浏览 110回答 1
1回答

偶然的你

而不是wg.Done()用defer wg.Done()按照它的写作方式,你的戈鲁丁信号表明,当它们开始运行时,工作已经消失,而不是当它们结束时,允许主戈鲁廷继续和退出。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go