pathletboy
2022-05-18 15:05:54 +08:00
为了灵活性
go 中,可以对 nil 值 channel 进行读写操作,当对值为 nil 的 channel 进行读取操作时会阻塞,但是对值为 nil 值的 channel 调用 close()会 panic 。使用 nil 值 channel 可以帮助在 select 中禁用某个 select 分支,因为阻塞了所以都不会进入分支语句。
下面是 client-go 中对 nil 值 channel 和单向 channel 的使用的函数代码:
func (p *processorListener) pop() {
defer utilruntime.HandleCrash()
defer close(p.nextCh) // Tell .run() to stop
var nextCh chan<- interface{}
var notification interface{}
for {
select {
case nextCh <- notification:
// Notification dispatched
var ok bool
notification, ok = p.pendingNotifications.ReadOne()
if !ok { // Nothing to pop
nextCh = nil // Disable this select case
}
case notificationToAdd, ok := <-p.addCh:
if !ok {
return
}
if notification == nil { // No notification to pop (and pendingNotifications is empty)
// Optimize the case - skip adding to pendingNotifications
notification = notificationToAdd
nextCh = p.nextCh
} else { // There is already a notification waiting to be dispatched
p.pendingNotifications.WriteOne(notificationToAdd)
}
}
}
}