Example for sync.WaitGroup correct?

Yes, this example is correct. It is important that the wg.Add() happens before the go statement to prevent race conditions. The following would also be correct: func main() { var wg sync.WaitGroup wg.Add(1) go dosomething(200, &wg) wg.Add(1) go dosomething(400, &wg) wg.Add(1) go dosomething(150, &wg) wg.Add(1) go dosomething(600, &wg) wg.Wait() fmt.Println(“Done”) } However, it is rather … Read more

How to wait for all goroutines to finish without using time.Sleep?

You can use sync.WaitGroup. Quoting the linked example: package main import ( “net/http” “sync” ) func main() { var wg sync.WaitGroup var urls = []string{ “http://www.golang.org/”, “http://www.google.com/”, “http://www.somestupidname.com/”, } for _, url := range urls { // Increment the WaitGroup counter. wg.Add(1) // Launch a goroutine to fetch the URL. go func(url string) { // … Read more

Prevent the main() function from terminating before goroutines finish in Golang

Simplest, cleanest and “scalable” way to do it is to use a sync.WaitGroup: var wg = &sync.WaitGroup{} func printElo() { defer wg.Done() fmt.Printf(“Elo\n”) } func printHello() { defer wg.Done() fmt.Printf(“Hello\n”) } func main() { fmt.Printf(“This will print.”) i := 0 for i < 10 { wg.Add(1) go printElo() wg.Add(1) go printHello() i++ } wg.Wait() } … Read more