How to use WaitGroup to delay execution of the main function in Go by example?

Use WaitGroup to delay execution of the main function until after all goroutines are completes

In Go, you can use a WaitGroup to delay the execution of the main function until after all goroutines have completed. A WaitGroup is a synchronization primitive that allows you to block the execution of a goroutine until a set of related goroutines have completed.

Example

package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	var wg sync.WaitGroup

	for i := 1; i <= 3; i++ {
		wg.Add(1)
		go func(i int) {
			fmt.Printf("Starting goroutine %d\n", i)
			time.Sleep(2 * time.Second)
			fmt.Printf("Ending goroutine %d\n", i)
			wg.Done()
		}(i)
	}

	wg.Wait()
	fmt.Println("All goroutines have completed")
}

Output

Starting goroutine 3
Starting goroutine 2
Starting goroutine 1
Ending goroutine 3
Ending goroutine 1
Ending goroutine 2
All goroutines have completed

Explaination:

we create a WaitGroup called wg to synchronize the goroutines. We then create three goroutines using a for loop and increment the wait group counter using wg.Add(1) before each goroutine is launched.

Inside each goroutine, we print a message to the console indicating that the goroutine has started, simulate some work using time.Sleep(), and then print another message indicating that the goroutine has completed. Finally, we call wg.Done() to decrement the wait group counter.

After all goroutines have been launched, we call wg.Wait() to block the execution of the main function until all goroutines have completed. Once all goroutines have completed, we print a message to the console indicating that all goroutines have completed.