Value Retrieval from Closed Channels
In Go, closing a channel signals the absence of future value transmissions. Surprisingly, it is possible to retrieve values from a closed channel, even after the Go specification states that receive operations should return zero values without blocking.
Let's delve into the example code to understand this behavior:
package main import ( "fmt" "sync" "time" ) func main() { iCh := make(chan int, 99) var wg sync.WaitGroup go func() { for i := 0; i < 5; i++ { wg.Add(1) go func(i int) { defer wg.Done() iCh <- i }(i) } // Close the channel once all values are sent wg.Wait() close(iCh) }() // Sleep for 5 seconds, allowing all goroutines to complete time.Sleep(5 * time.Second) print("the channel should be closed by now\n") for i := range iCh { fmt.Printf("%v\n", i) } print("done") }
Despite the channel being closed before the range statement, we can still retrieve and print the values. This is because the channel buffer initially contained 5 previously sent values.
The Go Specification
The Go Programming Language Specification states that after closing a channel, receive operations should return zero values without blocking. However, this only applies after receiving all previously sent values. In our example, the 5 previously sent values remain buffered in the channel, allowing us to retrieve them even after closure.
By default, channels created with make have a capacity of zero, which means that sending a value blocks until it is received. In the case of our example, the channel has a capacity of 99, which allows values to be sent without blocking.
Conclusion
While closing a channel signals the absence of future value transmissions, it does not immediately empty the channel buffer. Previously sent values can still be retrieved using receive operations, even if the channel is closed. This behavior demonstrates the importance of ensuring that all values are received before relying on the zero value being returned by receive operations.
The above is the detailed content of Can Values Be Retrieved from a Closed Go Channel After All Sent Values Have Been Buffered?. For more information, please follow other related articles on the PHP Chinese website!