To safely close multiple channels using a select statement and sync in Golang, you can follow these steps:
import (
"sync"
)
ch1 := make(chan bool)
ch2 := make(chan bool)
wg := sync.WaitGroup{}
func safeClose(ch chan bool) {
defer wg.Done() // Notify wait group that the function is done
select {
case _, ok := <- ch:
if ok {
close(ch) // Close the channel if it still open
}
default:
// Channel is already closed
}
}
wg.Add(2) // Number of channels to close
go safeClose(ch1)
go safeClose(ch2)
wg.Wait() // Wait until all the goroutines are done
By following these steps, you can safely close multiple channels using a select statement and sync in Golang.