我正在调查渠道行为,我对他们的行为感到很困惑。规范说After calling close, and after any previously sent values have been received, receive operations will return the zero value for the channel's type without blocking.但是,即使到那时通道已关闭,我似乎仍然获得范围语句中的值。这是为什么?
package main
import "fmt"
import "sync"
import "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)
}
wg.Wait()
close(iCh)
}()
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")
}
编辑:似乎如果我close在通道范围之前移动语句,它将永远关闭它。所以我想知道为什么它也不适用于“time.Sleep”技巧。到那个时候(5 秒)所有的 go 例程都应该已经完成并且通道关闭了,不是吗?
慕侠2389804
相关分类