To safely close a channel and signal completion using sync.WaitGroup
in Go, you can follow these steps:
import (
"sync"
)
sync.WaitGroup
variable and initialize it:var wg sync.WaitGroup
wg.Add(1)
ch := make(chan bool)
go func() {
defer wg.Done()
// Do the required task
// ...
// Signal completion by writing to the channel
ch <- true
}()
sync.WaitGroup.Wait()
:go func() {
wg.Wait()
// Close the channel after all goroutines have finished
close(ch)
}()
for val := range ch {
// Process received value
// ...
}
func main() {
// ...
}
By using sync.WaitGroup
and a buffered channel, you can safely close the channel and signal completion without worrying about race conditions.