Home >Backend Development >Golang >How to Gracefully Close a Go Channel of Unknown Length?
When working with channels in Go, it's crucial to determine the appropriate time to close them. This presents a challenge when the channel's length is unknown.
Consider the following scenario:
package main import ( "fmt" "time" ) func main() { ch := make(chan int) go func() { for i := 0; i < 100; i++ { ch <- i } close(ch) }() for v := range ch { fmt.Println(v) } }
In this example, a goroutine sends 100 values to the channel, with the intention of closing it once all values have been sent. However, this approach raises concerns. Specifically:
To address these issues, a sync.WaitGroup can be used to synchronize the closure of the channel with the completion of the sending goroutine.
package main import ( "fmt" "sync" "time" ) func main() { var wg sync.WaitGroup ch := make(chan int) wg.Add(1) // Increment counter for sender goroutine go func() { defer wg.Done() // Decrement counter when goroutine completes for i := 0; i < 100; i++ { ch <- i } close(ch) }() go func() { wg.Wait() // Wait until the sender goroutine completes close(ch) // Close the channel after all values have been sent }() for v := range ch { fmt.Println(v) } }
The above is the detailed content of How to Gracefully Close a Go Channel of Unknown Length?. For more information, please follow other related articles on the PHP Chinese website!