不带缓冲的通道
这种类型的通道要求发送 goroutine 和接收 goroutine 同时准备好,才能完成发送和接收操作。
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan int, 0)
go func() {
defer func() {
fmt.Println("recycle")
}()
a := <- c
fmt.Println("read",a)
}()
c <- 11
fmt.Println("write")
time.Sleep(time.Second*5)
}
输出:
read 11
recycle
write
可以看出发送端会一直阻塞到这个goroutine完全退出。
带缓冲的通道
上面代码第10行,改成缓冲为1个的通道
c := make(chan int, 1)
输出:
write
read 11
recycle
就变成了:我先走了,你们慢慢退出。