ANi*_*sus 95
您可以使用默认select语句.如果无法执行任何情况,例如发送到完整通道,则语句将执行以下操作:
package main
import "fmt"
func main() {
    ch := make(chan int, 1)
    // Fill it up
    ch <- 1
    select {
    case ch <- 2: // Put 2 in the channel unless it is full
    default:
        fmt.Println("Channel full. Discarding value")
    }
}
输出:
频道已满.抛弃价值
游乐场: http ://play.golang.org/p/1QOLbj2Kz2
不发送检查
len(ch)如Go规范中所述,还可以通过使用来检查在通道中排队的元素的数量.结合使用cap,我们可以在不发送任何数据的情况下检查通道是否已满.
if len(ch) == cap(ch) {
    // Channel was full, but might not be by now
} else {
    // Channel wasn't full, but might be by now
}
请注意,在您输入if块时,比较结果可能无效
Von*_*onC 12
相反,我选择删除发送到缓冲通道的项目.
这被称为"溢出通道",你会发现ANisus的答案在eapache/channels/overflowing_channel.go:
for elem := range ch.input {
    // if we can't write it immediately, drop it and move on
    select {
    case ch.output <- elem:
    default:
    }
}
close(ch.output)
但该项目的eapache/channels也实现了其他策略:
OverflowingChannelChannel以永不阻止编写器的方式实现接口.OverflowingChannel其缓冲区已满时对于相反的行为(丢弃最旧的元素,而不是最新的元素)请参阅
RingChannel.
| 归档时间: | 
 | 
| 查看次数: | 26560 次 | 
| 最近记录: |