我试图通过运行小程序来学习频道。我不明白下面的程序,因为它给出了一个奇怪的输出:
func squares(c chan int) {
for i := 0; i < 4; i++ {
num := <-c
fmt.Println(num * num)
}
}
func main() {
c := make(chan int, 3)
go squares(c)
c <- 1
c <- 2
c <- 3
c <- 4
fmt.Println(runtime.NumGoroutine())
time.Sleep(time.Second)
fmt.Println(runtime.NumGoroutine())
}
在执行这个程序时,我看到第一次它打印活动 goroutine 的数量为 2。然后一秒钟后,它的输出为 1。这真的很奇怪。
看了几篇博客,没看懂。那么,在 goroutine 停止工作的那一秒内,究竟发生了什么变化?
慕的地10843
潇潇雨雨
jeck猫
相关分类