Go goroutines are not running

Issue

Today, I learned about buffered channels. The issue I am facing understanding is, I am using WaitGroup’s Wait function for all the goroutines to execute.

But not all the goroutines are executing and the program ends before without waiting for all the goroutines to finish.

Code:

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))
}

Am I missing something here?

Solution

Instead of

wg.Done()

use

defer wg.Done()

The way it is written, your goroutines signal that the work is gone when they start running, not when they end, allowing the main goroutine to continue and exit.

Answered By – Burak Serdar

Answer Checked By – Clifford M. (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.