[Golang] Wait For Goroutines to Finish


This post shows two approaches to wait for all goroutines to finish.

Channel [1]

Wait for all goroutines to finish via channels:

Run Code on Go Playground

package main

import (
      "fmt"
)

func routine(site string, c chan int) {
      defer func() { c <- 1 }()

      // do something
      fmt.Println(site)
}

func main() {
      c := make(chan int)

      sites := []string{
              "https://www.google.com/",
              "https://duckduckgo.com/",
              "https://www.bing.com/"}

      for _, site := range sites {
              go routine(site, c)
      }

      // wait all goroutines to finish
      for i := 0; i < len(sites); i++ {
              <-c
      }
}

sync.WaitGroup [4]

Wait for all goroutines to finish via sync.WaitGroup:

Run Code on Go Playground

package main

import (
      "fmt"
      "sync"
)

var wg sync.WaitGroup

func routine(site string) {
      // Decrement the counter when the goroutine completes.
      defer wg.Done()

      // do something
      fmt.Println(site)
}

func main() {
      sites := []string{
              "https://www.google.com/",
              "https://duckduckgo.com/",
              "https://www.bing.com/"}

      for _, site := range sites {
              // Increment the WaitGroup counter.
              wg.Add(1)

              go routine(site)
      }

      // wait all goroutines to finish
      wg.Wait()
}

Tested on: The Go Playground


References:

[1]Waiting for all goroutines to finish before ending main - Google Groups
[2]DuckDuckGo Search: golang wait for goroutine to finish
[3]Google Search: golang wait for goroutine to finish
[4]优雅の使用sync.WaitGroup - hawkingrei | Blog
[5]goroutine anti-pattern? : golang
[6]Non blocking way of notifying a goroutine, by many at once : golang
[7]Can someone explain why this program isn't faster with goroutines? : golang
[8]How to store/retrieve channels in sync map? : golang
[9]Goroutines blocking on channels vs goroutines blocking on system calls : golang
[10]Is it safe to assume that the compiler will make goroutines cooperative regardless of the code? : golang
[11]Thread safe access to struct members : golang
[12]Scheduling In Go : Part III : golang
[13]Help understanding channel blocking : golang