How to use sync.WaitGroup to wait for a group of Goroutines to complete their tasks in Golang?

To wait for a group of Goroutines to complete their tasks in Golang, you can use the sync.WaitGroup package.

Here is an example of how to use sync.WaitGroup:

  1. Import the necessary packages:
import ( "sync" )
  1. Create a new sync.WaitGroup:
var wg sync.WaitGroup
  1. Increment the wait group counter before starting each Goroutine:
wg.Add(1)
  1. Start your Goroutines, passing the sync.WaitGroup as an argument:
go yourGoroutine(&wg)
  1. Inside your Goroutine, when it has completed its task, call Done() on the sync.WaitGroup:
func yourGoroutine(wg *sync.WaitGroup) { defer wg.Done() // Your Goroutine logic here }
  1. Finally, to wait for all Goroutines to complete, call Wait() on the sync.WaitGroup:
wg.Wait()

By calling Wait(), the program will block until all Goroutines have completed their tasks and called Done() on the sync.WaitGroup.

Make sure to initialize the sync.WaitGroup before starting your Goroutines, increment the wait group counter before each Goroutine, call Done() when a Goroutine completes its task, and call Wait() to wait for all Goroutines to complete.