无缓冲通道
只有当读写都准备好时才不会被阻塞
func main() {
ch := make(chan struct{})
go func() {
<-ch
}()
ch <- struct{}{}
fmt.Println("done")
}
输出:
done
Process finished with exit code 0
有缓冲通道
- 当有缓冲通道长度未满时,写入是无阻塞的
func main() {
ch := make(chan struct{}, 2)
ch <- struct{}{}
fmt.Println("done")
}
输出:
done
Process finished with exit code 0
- 当有缓冲通道长度已满时,写入是阻塞的
func main() {
ch := make(chan struct{}, 2)
go func() {
ch <- struct{}{}
fmt.Println("append ch")
}()
for i := 0; i < 2; i++ {
ch <- struct{}{}
}
time.Sleep(time.Second)
fmt.Println("done")
}
输出:
done
Process finished with exit code 0
网友评论