【发布时间】:2020-12-28 16:09:20
【问题描述】:
我有以下 go 脚本,我对读取数据的通道和 go 例程的执行顺序有疑问。
package main
import "fmt"
func squares(c chan int) {
fmt.Println("started squares goroutine...")
for num := range c {
//num := <-c
fmt.Println(num * num)
}
fmt.Println("exiting squares goroutine...")
}
func main() {
fmt.Println("main() started")
c := make(chan int, 3)
go squares(c)
c <- 1
printChannel(c)
c <- 2
printChannel(c)
c <- 3
printChannel(c)
c <- 4
fmt.Println("after publish 4")
printChannel(c)
c <- 5
fmt.Println("after publish 5")
printChannel(c)
c <- 6
printChannel(c)
c <- 7
printChannel(c)
c <- 8
printChannel(c)
fmt.Println("main() stopped")
}
func printChannel(c chan int) {
fmt.Println("length: ",len(c))
fmt.Println("capacity: ",cap(c))
}
输出:
main() started
length: 1
capacity: 3
length: 2
capacity: 3
length: 3
capacity: 3
started squares goroutine...
1
4
9
16
after publish 4
length: 0
capacity: 3
after publish 5
length: 0
capacity: 3
length: 1
capacity: 3
length: 2
capacity: 3
length: 3
capacity: 3
main() stopped
问题:
-
创建的通道 ch 的容量为 3,但在将 4 发布到通道之前,不会在方块 go 例程中读取通道,如果容量为 3,则通道中存储了 4
-
从channel读取完所有数字后,再次将数字5发布到channel,但是channel的长度还是0,为什么?
代码的Goplayground链接:https://play.golang.org/p/TmCcZt5n58f
【问题讨论】:
标签: go concurrency channel goroutine