我刚接触golang。今天测试通道在Golang中的工作方式时,我感到非常困惑。
根据教程:
仅当缓冲区已满时才发送到缓冲的通道块。当缓冲区为空时接收块。
我的测试程序如下所示:
package main
import "fmt"
func main() {
ch := make(chan int, 2)
go func(ch chan int) int {
for i := 0; i < 10; i++ {
fmt.Println("goroutine: GET ", <-ch)
}
return 1
}(ch)
for j := 0; j < 10; j++ {
ch <- j
fmt.Println("PUT into channel", j)
}
}
我得到这样的输出:
PUT into channel 0
PUT into channel 1
goroutine: GET 0
goroutine: GET 1
goroutine: GET 2
PUT into channel 2
PUT into channel 3
PUT into channel 4
PUT into channel 5
goroutine: GET 3
goroutine: GET 4
goroutine: GET 5
goroutine: GET 6
PUT into channel 6
PUT into channel 7
PUT into channel 8
PUT into channel 9
请注意,编号2是从通道中取出的,甚至没有放入通道中。为什么会这样?
蝴蝶刀刀
相关分类