bigwhite / GoProgrammingFromBeginnerToMaster

Go语言精进之路书籍配套代码
Apache License 2.0
247 stars 82 forks source link

Blocked on closing a chan in chapter 6 #26

Closed sharework-cn closed 2 years ago

sharework-cn commented 2 years ago

大神你好,在Airport Security Check的例子中(chapter6/source),下面语句似乎会被阻塞:

`func main() { passengers := 30 queue := make(chan struct{}, 30) newAirportSecurityCheckChannel("channel1", queue) newAirportSecurityCheckChannel("channel2", queue) newAirportSecurityCheckChannel("channel3", queue)

time.Sleep(5 * time.Second) // 保证上述三个goroutine都已经处于ready状态
for i := 0; i < passengers; i++ {
    queue <- struct{}{}
}
time.Sleep(5 * time.Second)
    close(queue) // 为了打印各通道的处理时长  <---- 这条语句会被阻塞
time.Sleep(1000 * time.Second)

}`

请问能否分析下,以及列举什么情况下关闭一个队列会被阻塞呢?谢谢。

sharework-cn commented 2 years ago

我知道原因了,没注意到最后是以time.Sleep(1000 * time.Second)结尾的。