这篇文章没看懂,简单说下就是channel初始化的时候,make了缓存长度的话,就是带缓存的,没有make长度,就是不带缓存的。带缓存的只要缓存没有满,往channel里面写东西和从channel里面读东西就都是异步的,不会被阻塞的。但是如果是不带缓存的,必须是发送的东西有人收到后才能继续下一次发送;或者是接受的东西必须收到后才能继续下一次的接受。
func main() {
jobs := make(chan int, 1)
done := make(chan bool)
go func() {
//fmt.Println("GoStart")
for i := 1; ; i++ {
//fmt.Println("GoforSTART", i)
j, more := <-jobs
if more {
fmt.Println("received job", j)
} else {
fmt.Println("received all jobs")
done <- true
return
}
//fmt.Println("GoforEND", i)
}
}()
for j := 1; j <= 3; j++ {
//fmt.Println("OutFOR", j)
jobs <- j
fmt.Println("sent job", j)
}
close(jobs)
fmt.Println("sent all jobs")
<-done
}
以参考的文章里面的程序举例,如上图,当有缓存的时候,执行结果如下(每次结果不一样),只有当缓存满的时候才会被阻塞:
sent job 1
sent job 2
received job 1
received job 2
received job 3
sent job 3
sent all jobs
received all jobs
或者
received job 1
sent job 1
sent job 2
sent job 3
sent all jobs
received job 2
received job 3
received all jobs
当没有缓存时,执行结果如下(每次结果不一样):
received job 1
sent job 1
sent job 2
received job 2
received job 3
sent job 3
sent all jobs
received all jobs
或者
sent job 1
received job 1
received job 2
sent job 2
sent job 3
sent all jobs
received job 3
received all jobs
或者