为什么 Go 在写入关闭的通道时会出现恐慌?
虽然可以使用value, ok := <-channel习语从通道读取,因此可以测试 ok 结果是否命中封闭通道:
// reading from closed channel
package main
import "fmt"
func main() {
ch := make(chan int, 1)
ch <- 2
close(ch)
read(ch)
read(ch)
read(ch)
}
func read(ch <-chan int) {
i,ok := <- ch
if !ok {
fmt.Printf("channel is closed\n")
return
}
fmt.Printf("read %d from channel\n", i)
}
输出:
read 2 from channel
channel is closed
channel is closed
在Playground上运行“从封闭频道读取”
写入可能关闭的通道更加复杂,因为如果您只是在通道关闭时尝试写入,Go 会恐慌:
//writing to closed channel
package main
import (
"fmt"
)
func main() {
output := make(chan int, 1) // create channel
write(output, 2)
close(output) // close channel
write(output, 3)
write(output, 4)
}
// how to write on possibly closed channel
func write(out chan int, i int) (err error) {
defer func() {
// recover from panic caused by writing to a closed channel
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
fmt.Printf("write: error writing %d on channel: %v\n", i, err)
return
}
fmt.Printf("write: wrote %d on channel\n", i)
}()
out <- i // write on possibly closed channel
return err
}
输出:
write: wrote 2 on channel
write: error writing 3 on channel: send on closed channel
write: error writing 4 on channel: send on closed channel
在Playground上运行“写入封闭频道”
据我所知,没有一个更简单的习惯用法可以在不惊慌的情况下写入可能已关闭的通道。为什么不?这种读写之间的不对称行为背后的原因是什么?
泛舟湖上清波郎朗
相关分类