说明
func make(t Type, size ...IntegerType) Type
指出该值在同一时刻最多可以容纳 size
个元素值。
如果我们发送给该通道的元素值未被取走,那么该通道最多可以暂存(或者说缓冲)size
个元素值。
当发送第size +1
个元素值后, 会造成当前Goroutine的堵塞(在chan<-
时会卡住,等chan有空间时才可以<-
并且进行后面的代码)
示例
代码
func HelloMakeChanSize() {
size := 0
c1 := make(chan int, size)
go func() {
for i := 0; i < 4; i++ {
val := i*10 + 7
fmt.Println(time.Now(), "<- ", val, "at", i)
c1 <- i*10 + 7
}
c1 <- 0
}()
time.Sleep(time.Second * 3)
fmt.Println("After Sleep")
for val := range c1 {
fmt.Println(time.Now(), "receive:", val)
if val == 0 {
break
}
}
}
c1 := make(chan int,size)
中的size
修改为不同值, 会有不同的输出效果
无size 或 size=0 时的输出结果
第一次c1<-
时, 由于没有立刻被取走func就会堵塞住,等3秒后c1被读取才进行后面的代码
2019-05-17 14:57:29.2314327 +0800 CST m=+0.003910401 <- 7 at 0
After Sleep
2019-05-17 14:57:32.2321627 +0800 CST m=+3.004754901 receive: 7
2019-05-17 14:57:32.2321627 +0800 CST m=+3.004754901 <- 17 at 1
2019-05-17 14:57:32.2321627 +0800 CST m=+3.004754901 <- 27 at 2
2019-05-17 14:57:32.2321627 +0800 CST m=+3.004754901 receive: 17
2019-05-17 14:57:32.2321627 +0800 CST m=+3.004754901 receive: 27
2019-05-17 14:57:32.2321627 +0800 CST m=+3.004754901 <- 37 at 3
2019-05-17 14:57:32.2321627 +0800 CST m=+3.004754901 receive: 37
2019-05-17 14:57:32.2321627 +0800 CST m=+3.004754901 receive: 0
size=1时的输出结果
第二次c1<-
时,由于第一个没有取走, 会堵塞
2019-05-17 14:57:57.7795593 +0800 CST m=+0.004894501 <- 7 at 0
2019-05-17 14:57:57.819622 +0800 CST m=+0.044958701 <- 17 at 1
After Sleep
2019-05-17 14:58:00.7799573 +0800 CST m=+3.005407001 receive: 7
2019-05-17 14:58:00.7799573 +0800 CST m=+3.005407001 receive: 17
2019-05-17 14:58:00.7799573 +0800 CST m=+3.005407001 <- 27 at 2
2019-05-17 14:58:00.7799573 +0800 CST m=+3.005407001 <- 37 at 3
2019-05-17 14:58:00.7799573 +0800 CST m=+3.005407001 receive: 27
2019-05-17 14:58:00.7799573 +0800 CST m=+3.005407001 receive: 37
2019-05-17 14:58:00.7799573 +0800 CST m=+3.005407001 receive: 0
size=3时的输出结果
2019-05-17 14:58:24.7116812 +0800 CST m=+0.004888401 <- 7 at 0
2019-05-17 14:58:24.7449182 +0800 CST m=+0.038126701 <- 17 at 1
2019-05-17 14:58:24.7449182 +0800 CST m=+0.038126701 <- 27 at 2
2019-05-17 14:58:24.7449182 +0800 CST m=+0.038126701 <- 37 at 3
After Sleep
2019-05-17 14:58:27.7108697 +0800 CST m=+3.004191401 receive: 7
2019-05-17 14:58:27.7108697 +0800 CST m=+3.004191401 receive: 17
2019-05-17 14:58:27.7108697 +0800 CST m=+3.004191401 receive: 27
2019-05-17 14:58:27.7108697 +0800 CST m=+3.004191401 receive: 37
2019-05-17 14:58:27.7108697 +0800 CST m=+3.004191401 receive: 0