Member-only story

Go goroutine management, WaitGroup and Context

Weekly Dev Blog
3 min readApr 19, 2021

--

There are two classic way to handle concurrency in go, WaitGroup and Context

What is WaitGroup

A WaitGroup waits for a collection of goroutines to finish

func main() {
var wg sync.WaitGroup
wg.Add(2)
go func() {
time.Sleep(2*time.Second)
fmt.Println("1st task done")
wg.Done()
}()
go func() {
time.Sleep(2*time.Second)
fmt.Println("2nd task done")
wg.Done()
}()
wg.Wait()
fmt.Println("Finish")
}

The program only finishes when the 2 goroutine finished. Otherwise, it will wait for it.
This is useful when we want a program to wait for all tasks to finish.

However, sometimes we want to actively cancel a goroutine instead of wait for it to finish. An example can be monitoring. We want to exit monitoring instead of wait for it to finish (it will never finish). We can use channel for this usecase.

Channel

we can use channel + select to repeatedly checking on a global variable to notify the end of a process

func main() {
stop := make(chan bool)
go func() {
for {
select {
case <-stop:
fmt.Println("monitoring finish, exit")
return
default:
fmt.Println("gorouting monitoring")
time.Sleep(2 * time.Second)
}
}
}()
time.Sleep(10 * time.Second)
fmt.Println("notify end of monitoring")
stop<- true
//

--

--

No responses yet