遇到了一种情况,我不确定从通道顺序读取时它在 golang 中的行为方式,这应该以来自“输出通道”的完成信号结束。这是一个描述我的代码的示例:
func f() {
doneCh := make(chan struct{})
trafficCh := make(chan interface{})
go write(doneCh, trafficCh)
read(doneCh, trafficCh)
}
func write(doneCh chan<- struct{}, sendCh chan<- interface{}) {
defer func() {
doneCh <- struct{}{}
}()
for {
// Send something in sendCh
}
}
func read(doneCh <-chan struct{}, recvCh <-chan interface{}) {
for {
select {
case <-doneCh:
return
case item := <-recvCh:
// Something do with item
}
}
}
根据标准,如果 select 在不同的通道中收到了多条消息,那么它会随机选择一条。是否有可能当 select 选择一个频道时,它会在doneChand中看到消息recvCh,即 将发生未定义的行为,我们可以在不读取所有元素的情况下结束读取。
