Go goroutine management, WaitGroup and Context
There are two classic way to handle concurrency in go, WaitGroup and Context What is WaitGroup WaitGroup wait for multiple goroutines to finish content_copy 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 content_copy func main() { stop := ...