问题
The following program never prints "Full". With fmt.Println(len(choke))
uncommented, the program outputs "Full" when the channel is full.
package main
import (
"fmt"
)
func main() {
choke := make(chan string, 150000)
go func() {
for i := 0; i < 10000000; i++ {
choke <- string(i)
fmt.Println("i=", i)
}
}()
for {
//fmt.Println(len(choke))
if len(choke) >= 150000 {
fmt.Println("Full")
}
}
}
@tim-heckman explained the cause of this behavior in OP.
How do I detect a channel is full without using a hot loop?
回答1:
Use a select
statement on the write side. It will write to the channel if there is buffer available or a receiver waiting; it will fallthrough to the default
case if the channel is full.
func main() {
choke := make(chan string, 150000)
var i int
for {
select {
case choke <- string(i):
i++
default:
fmt.Println("Full")
return
}
}
}
来源:https://stackoverflow.com/questions/48939522/checking-channel-length-becomes-unresponsive-in-for-lenc