How to safely close a channel to signal completion using sync.WaitGroup in Golang?

To safely close a channel and signal completion using sync.WaitGroup in Go, you can follow these steps:

  1. Import the necessary packages:
import ( "sync" )
  1. Create a sync.WaitGroup variable and initialize it:
var wg sync.WaitGroup wg.Add(1)
  1. Create a buffered channel to communicate between goroutines:
ch := make(chan bool)
  1. Start a goroutine to perform the required task:
go func() { defer wg.Done() // Do the required task // ... // Signal completion by writing to the channel ch <- true }()
  1. Wait for the goroutine to finish using sync.WaitGroup.Wait():
go func() { wg.Wait() // Close the channel after all goroutines have finished close(ch) }()
  1. In the main goroutine, use a loop to receive values from the channel until it's closed:
for val := range ch { // Process received value // ... }
  1. Run the main goroutine:
func main() { // ... }

By using sync.WaitGroup and a buffered channel, you can safely close the channel and signal completion without worrying about race conditions.