How to wait for a goroutine to finish in Golang?



We know that goroutines can be a bit tricky at first, and often we find cases where the main goroutines will exit without giving a chance to the inside goroutines to execute.

In order to be able to run the goroutines until the finish, we can either make use of a channel that will act as a blocker or we can use waitGroups that Go's sync package provides us with.

Let's first explore a case where we have a single goroutines that we want to finish and then do some other work.

Example 1

Consider the code shown below.

package main
import (
   "fmt"
)
func check(ch chan bool){
   fmt.Println("Inside check")
   ch <- true
}
func main() {
   ch := make(chan bool)
   go func(){
      check(ch)
   }()
   <-ch
   fmt.Println("Done")
}

In the above code, the line <-ch is the most important one and if we remove it, then the anonymous goroutine won't get a chance to execute properly.

Output

When we run the code, it will produce the following output in the terminal.

Inside check
Done

In the above code, we saw a case that has only one goroutine but let's consider one where there are multiple goroutines and we want to wait for all of them to finish.

Example 2

Consider the code shown below.

package main
import (
   "fmt"
   "sync"
)
func check(count int, wg *sync.WaitGroup) {
   defer wg.Done()
   fmt.Println("Inside check", count)
}
func main() {
   count := 3
   var wg sync.WaitGroup
   wg.Add(count)
   for i := 1; i <= count; i++ {
      go check(i, &wg)
   }
   wg.Wait()
   fmt.Println("Done")
}

In the above code, we spanned multiple goroutines inside the for loop and we passed the waitGroup as an argument to the check function. The most important part that allows us to wait for the completion of these goroutines is the Wait() function.

Output

When we run the code, it will produce the following output in the terminal.

Inside check 3
Inside check 2
Inside check 1
Done

It should be noted that the order of the count in the above goroutine may vary, but it is for sure that you will get the "Done" printed only if all the goroutines have been executed.


Advertisements